暂无分类
暂无标签
发布于2021-02-24 11:50 阅读(471) 评论(0) 点赞(14) 收藏(5)
0
1
2
3
4
5
使用selenium自动化时,一个很烦的问题就是chrome会自动更新,然后chromedriver的版本就会不兼容,每次要查询版本下载解压很烦,因此开始寻找如何用脚本自动更新。
网上找到了一些脚本,但是感觉略显繁琐,因此我就自己修改了一下,逻辑很简洁:
import os
import re
import winreg
import zipfile
import requests
base_url = 'http://npm.taobao.org/mirrors/chromedriver/'
version_re = re.compile(r'^[1-9]\d*\.\d*.\d*') # 匹配前3位版本号的正则表达式
def getChromeVersion():
"""通过注册表查询chrome版本"""
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Google\\Chrome\\BLBeacon')
value, t = winreg.QueryValueEx(key, 'version')
return version_re.findall(value)[0] # 返回前3位版本号
except WindowsError as e:
# 没有安装chrome浏览器
return "1.1.1"
def getChromeDriverVersion():
"""查询Chromedriver版本"""
outstd2 = os.popen('chromedriver --version').read()
try:
version = outstd2.split(' ')[1]
version = ".".join(version.split(".")[:-1])
return version
except Exception as e:
return "0.0.0"
def getLatestChromeDriver(version):
# 获取该chrome版本的最新driver版本号
url = f"{base_url}LATEST_RELEASE_{version}"
latest_version = requests.get(url).text
print(f"与当前chrome匹配的最新chromedriver版本为: {latest_version}")
# 下载chromedriver
print("开始下载chromedriver...")
download_url = f"{base_url}{latest_version}/chromedriver_win32.zip"
file = requests.get(download_url)
with open("chromedriver.zip", 'wb') as zip_file: # 保存文件到脚本所在目录
zip_file.write(file.content)
print("下载完成.")
# 解压
f = zipfile.ZipFile("chromedriver.zip", 'r')
for file in f.namelist():
f.extract(file)
print("解压完成.")
def checkChromeDriverUpdate():
chrome_version = getChromeVersion()
print(f'当前chrome版本: {chrome_version}')
driver_version = getChromeDriverVersion()
print(f'当前chromedriver版本: {driver_version}')
if chrome_version == driver_version:
print("版本兼容,无需更新.")
return
print("chromedriver版本与chrome浏览器不兼容,更新中>>>")
try:
getLatestChromeDriver(chrome_version)
print("chromedriver更新成功!")
except requests.exceptions.Timeout:
print("chromedriver下载失败,请检查网络后重试!")
except Exception as e:
print(f"chromedriver未知原因更新失败: {e}")
if __name__ == "__main__":
checkChromeDriverUpdate()
0
1
2
3
4
5
6
7
8
9
作者:83whjh
链接: https://www.pythonheidong.com/blog/article/853281/cd8b8c5db8f7b7da28cb/
来源: python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!