Python Selenium自动化 - 自动管理chromedriver
- 之前我们介绍了如何使用Python Selenium做浏览器自动化测试,提供的详细示例已经很好地介绍了如何使用ChromeDriverManager来自动管理ChromeDriver。
如何使用ChromeDriverManager 来管理ChromeDriver
- 最近chrome自动更新了116版本,chromedriver仍停留在114版本,上文代码会在当前目录自动下载最新114版本chromedriver,只有当二者同步更新时可以正常使用。
解决方案:锁定旧版Chrome
Chrome自动更新迅速,较新的旧版Chrome难以寻找,一种简单的方法是锁定Chrome浏览器在较旧的版本,例如104。
你可以在这里找到安装包
Google Chrome Older Versions Download (Windows, Linux &Mac)
下载安装会下载到这个目录 C:\Program Files (x86)\Google
锁定方法可参考这篇文章
彻底关闭Chrome浏览器自动更新
然后我们使用chromedriver_autoinstaller模块,它可以自动检查当前Chrome浏览器版本,并下载匹配的最新chromedriver。
使用步骤:
- 安装chromedriver_autoinstaller
pip install chromedriver_autoinstaller
- 导入模块并调用install方法安装匹配chromedriver
import chromedriver_autoinstaller
chromedriver_autoinstaller.install()
- 创建ChromeDriver实例
driver = webdriver.Chrome()
完整代码及实例
这个版本的chromedriver会下载到C盘中的这个目录
C:\Users\你的用户名\.cache\selenium\chromedriver\win32\104.0.5112.79
import time
import chromedriver_autoinstaller
from selenium.webdriver.common.by import By
from selenium import webdriver
# 自动安装匹配版本的 Chromedriver,首次下载时间较长,
# 首次下载后使用时注释掉,否则会重复下载
chromedriver_autoinstaller.install()
# 创建一个 Chrome 浏览器实例
driver = webdriver.Chrome()
# 使用浏览器访问网页
driver.get("https://www.baidu.com")
driver.find_element(By.ID, "kw").send_keys("selenium")
driver.find_element(By.ID, "su").click()
time.sleep(2)
driver.quit()
以上代码第二次使用时需要通过注释避免重复下载,不够完善。
优化后代码
import time
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import os
import chromedriver_autoinstaller
# 获取当前文件所在目录的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 设置驱动下载目录为当前目录下的drivers文件夹
driver_path = os.path.join(current_dir, 'drivers')
os.makedirs(driver_path, exist_ok=True)
# 提示用户选择是否下载新的 Chromedriver
user_choice = input("是否更新 Chromedriver?(y/n): ")
if user_choice.lower() == 'y':
# 自动安装最新版本的 Chromedriver
chromedriver_autoinstaller.install(path=driver_path)
# 创建Service对象,传入chromedriver路径
chromedriver_path = os.path.join(driver_path, chromedriver_autoinstaller.get_chrome_version())
service = Service(chromedriver_path)
# 创建一个 Chrome 浏览器实例,传入驱动服务对象
driver = webdriver.Chrome(service=service)
else:
# 如果你不使用104版本的chrome,需要改成你之前下载好的路径,跳过下载
service = Service("drivers/104/chromedriver.exe")
driver = webdriver.Chrome(service=service)
# 使用浏览器访问网页
driver.get("https://www.baidu.com")
driver.find_element(By.ID, "kw").send_keys("selenium")
driver.find_element(By.ID, "su").click()
time.sleep(2)
# 关闭浏览器
driver.quit()
现在chromedriver的版本将永远和Chrome浏览器版本相匹配,避免了版本不兼容的问题。
总结
chromedriver_autoinstaller可以自动管理chromedriver版本,是Python Selenium测试者的必备工具。它可以提高代码可移植性,减少版本问题导致的失败。推荐结合使用,使得自动化测试更加稳定可靠。
2023-11-14
国内使用chromedriver_autoinstaller网络受限,你可以在这里下载我下载好的chromedriver
链接:https://pan.baidu.com/s/1GnJTPO-4JPB_j2wrYZZJ8A?pwd=97jn
提取码:97jn
然后使用
service = Service("drivers/104/chromedriver.exe")
实践Scrapy+Selenium自动化获取个人CSDN文章质量分
import csv
import time
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
option = Options()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')
option.add_argument('--headless') # 启用无头模式
service = Service("drivers/104/chromedriver.exe")
driver = webdriver.Chrome(options=option,service=service)
# 用于存储CSV数据的列表
data = []
#
# 打开CSV文件并读取内容
with open('data.csv','r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
# 每行包括两个字段:链接和标题
link, title = row
# 将链接和标题作为元组添加到数据列表中
data.append((link, title))
# 使用浏览器访问网页
driver.get("https://www.csdn.net/qc")
for link,title in data:
driver.find_element(By.CSS_SELECTOR, ".el-input__inner").send_keys(f"{link}",link)
driver.find_element(By.CSS_SELECTOR, ".trends-input-box-btn").click()
time.sleep(0.5)
soc = driver.find_element(By.XPATH, '//*[@id="floor-csdn-index_850"]/div/div[1]/div/div[2]/p[1]').text
print(title,soc)
time.sleep(1)
driver.quit()