博文配套视频课程:24小时实现从零到AI人工智能
ChromeDriver介绍
chromeDriver 是 google 为网站开发人员提供的自动化测试接口,WebDriver是一个开源工具,用于在许多浏览器上自动测试webapps。它提供了导航到网页,用户输入,JavaScript执行等功能
- ChromeDriver的安装一定要与Chrome的版本一致,不然就不起作用,查看chrom的版本则在浏览器地址栏输入:chrome://version/
- chromedriver下载地址: http://chromedriver.storage.googleapis.com/index.html
重构下载器增加ajax功能
首先要在setting.py中开启下载器中间件:JianshuDownloaderMiddleware
DOWNLOADER_MIDDLEWARES = {
'jianshu.middlewares.JianshuDownloaderMiddleware': 543,
}
重写process_request方法
class JianshuDownloaderMiddleware(object):
def __init__(self):
self.driver = webdriver.Chrome(executable_path=r"d:\chromedriver.exe")
def process_request(self, request, spider):
print('process_request.............')
# 访问请求的连接交给测试浏览器
self.driver.get(request.url)
# 防止页面加载过慢,等待1秒
time.sleep(1)
try:
while True:
show_more = self.driver.find_element_by_class_name('show-more')
show_more.click()
time.sleep(0.5)
except:
print('别在单击了,没有了..........')
source = self.driver.page_source
from scrapy.http.response.html import HtmlResponse
response = HtmlResponse(url=self.driver.current_url, body=source,request=request, encoding='utf-8')
return response