1. 确保您已经安装了Google浏览器,并且版本与WebDriver版本兼容。
2. 在Google浏览器中输入以下网址:chrome://version/,并在地址栏中按下回车键。
3. 在打开的页面中,找到"Google Chrome"的版本号。通常这个信息会显示在“Google Chrome x.x.x.x”或“Google Chrome xxx.xx.xxxxx.xx”格式的位置。
4. 打开Webdriver官方网站(https://chromedriver.chromium.org/downloads)。
5. 根据您浏览器的版本号,从可用的版本中选择与您Google浏览器版本兼容的WebDriver版本。
6. 然后,选择您计算机中的操作系统和软件位数(32位或64位)。
7. 安装所选择的WebDriver版本。
8. WebDriver文件会安装到系统的某个目录中。您可以通过以下方式找到它:
- 在安装路径中查找,通常在C:\Program Files (x86)\Google\Chrome\Application或C:\Program Files\Google\Chrome\Application等位置。
- 检查环境变量:将WebDriver的安装路径添加到环境变量中,然后使用命令行运行“chromedriver”命令,它会返回WebDriver的路径。
- 在浏览器启动时,在启动时指定WebDriver的路径,例如:webdriver.Chrome("path_to_chromedriver")。
在使用scrapy和selenium中,scrapy中间件的写法就是
import time
from scrapy import signals
from scrapy.http import HtmlResponse
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from scrapy.http.response.html import HtmlResponse
from selenium.webdriver.chrome.service import Service
class ScrapyDoubanDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def __init__(self):
options = webdriver.ChromeOptions()
# options.add_argument('disable-infobars') #去除警告
options.add_argument('headless') # 无头模式
self.driver = webdriver.Chrome(options=options)
# self.driver.maximize_window()
self.num = 10 # 需要滑滚页面的次数,想拿多一点数据就设置的大一点
def spider_opened(self, spider):
# 本地的chromediver路径
SELENIUM_DRIVER_EXECUTABLE = 'E:\chromediver\chromedriver.exe'
# 指定ChromeDriver的路径(新版)
service = Service(executable_path=SELENIUM_DRIVER_EXECUTABLE)
# 使用service对象启动WebDriver
self.driver = webdriver.Chrome(service=service)