当前位置:网站首页>Automatically update selenium driver chromedriver
Automatically update selenium driver chromedriver
2022-07-06 23:11:00 【Xiaoming - code entity】
Due to frequent automatic updates of Google viewer selenium The driver fails and needs to be downloaded again , How to make code update automatically selenium What about the driving method ?
selenium When the connection Google viewer throws an exception , Will display the current version of Google Explorer , We can go to selenium Drive the download website to get all version information , Then find a matching version to download and unzip .
For faster download speed , Here I choose the domestic mirror station :http://npm.taobao.org/mirrors/chromedriver/
It will redirect to :https://registry.npmmirror.com/binary.html?path=chromedriver/
Checked by developer tools , You can find the interface to get all the latest version information :https://registry.npmmirror.com/-/binary/chromedriver/
I match according to the first three numbers , Download the driver with the largest version number .
The final complete code is :
from selenium import webdriver
from selenium.common.exceptions import SessionNotCreatedException
import re
import os
import requests
import zipfile
import itertools
def getChromeDriver(options=None):
""" Code author : Xiaoming - Code entities xxmdmst.blog.csdn.net"""
try:
driver = webdriver.Chrome(options=options)
return driver
except SessionNotCreatedException as e:
driver_version = re.search(
"Chrome version ([\d.]+)", str(e)).group(1)
chrome_version = re.search(
"Current browser version is ([\d.]+) with", str(e)).group(1)
print(f" Driver version :{
driver_version}, Google Explorer version :{
chrome_version}, Are not compatible \n Start updating the driver ...")
res = requests.get(
"https://registry.npmmirror.com/-/binary/chromedriver/")
versions = [obj["name"][:-1] for obj in res.json() if re.match("\d+",
obj["name"]) and obj["name"].count(".") == 3]
versions = {
key: max(versions_split, key=lambda x: int(x[x.rfind(".")+1:]))
for key, versions_split in itertools.groupby(versions, key=lambda x: x[:x.rfind(".")])}
dest_version = versions[chrome_version[:chrome_version.rfind(".")]]
print(" The driver will be updated to ", dest_version)
file = f"chromedriver_{
dest_version}_win32.zip"
if not os.path.exists(file):
url = f"https://registry.npmmirror.com/-/binary/chromedriver/{
dest_version}/chromedriver_win32.zip"
print(" Driver download address :", url)
res = requests.get(url)
with open(file, 'wb') as f:
f.write(res.content)
else:
print(file, " The file has been downloaded to the current directory , Next, directly use cache decompression to overwrite ...")
with zipfile.ZipFile(file) as zf:
zf.extract("chromedriver.exe", ".")
driver = webdriver.Chrome(options=options)
return driver
options = webdriver.ChromeOptions()
options.add_experimental_option(
'excludeSwitches', ['enable-logging', 'enable-automation'])
driver = getChromeDriver(options)
driver.get("https://www.baidu.com/")
Printing example when the driver is incompatible :
Driver version :100, Google Explorer version :102.0.5005.115, Are not compatible
Start updating the driver ...
The driver will be updated to 102.0.5005.61
Driver download address : https://registry.npmmirror.com/-/binary/chromedriver/102.0.5005.61/chromedriver_win32.zip
The download method developed above is relatively fast , If the code is too long , have access to webdriver_manager This library , adopt pip It can be installed directly :
pip install webdriver_manager
Then execute the following code from https://chromedriver.storage.googleapis.com Automatically download the matching driver , And return to the download location :
from webdriver_manager.chrome import ChromeDriverManager
ChromeDriverManager().install()
Print examples :
[WDM] - ====== WebDriver manager ======
[WDM] - Current google-chrome version is 102.0.5005
[WDM] - Get LATEST chromedriver version for 102.0.5005 google-chrome
[WDM] - There is no [win32] chromedriver for browser 102.0.5005 in cache
[WDM] - About to download new driver from https://chromedriver.storage.googleapis.com/102.0.5005.61/chromedriver_win32.zip
[WDM] - Driver has been saved in cache [C:\Users\ASUS\.wdm\drivers\chromedriver\win32\102.0.5005.61]
'C:\\Users\\ASUS\\.wdm\\drivers\\chromedriver\\win32\\102.0.5005.61\\chromedriver.exe'
In this way, we can directly set the position of the driver through the returned string :
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install(), options=None)
边栏推荐
- Redis 持久化机制
- 金融人士必读书籍系列之六:权益投资(基于cfa考试内容大纲和框架)
- View
- How to choose indoor LED display? These five considerations must be taken into account
- docker启动mysql及-eMYSQL_ROOT_PASSWORD=my-secret-pw问题解决
- 食品里的添加剂品种越多,越不安全吗?
- 【Unity】升级版·Excel数据解析,自动创建对应C#类,自动创建ScriptableObject生成类,自动序列化Asset文件
- (flutter2) as import old project error: inheritfromwidgetofexacttype
- Modules that can be used by both the electron main process and the rendering process
- 让 Rust 库更优美的几个建议!你学会了吗?
猜你喜欢

(1)长安链学习笔记-启动长安链
MySQL中正则表达式(REGEXP)使用详解

B站大佬用我的世界搞出卷积神经网络,LeCun转发!爆肝6个月,播放破百万

Hard core observation 545 50 years ago, Apollo 15 made a feather landing experiment on the moon

浅谈网络安全之文件上传

Unified Focal loss: Generalising Dice and cross entropy-based losses to handle class imbalanced medi

Traversal of a tree in first order, middle order, and then order

mysql连接vscode成功了,但是报这个错

ICLR 2022 | pre training language model based on anti self attention mechanism

Balanced Multimodal Learning via On-the-fly Gradient Modulation(CVPR2022 oral)
随机推荐
前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
(DART) usage supplement
The application of machine learning in software testing
Matlab tips (27) grey prediction
存币生息理财dapp系统开发案例演示
Efficient ETL Testing
专为决策树打造,新加坡国立大学&清华大学联合提出快速安全的联邦学习新系统
Uniapp setting background image effect demo (sorting)
NFTScan 开发者平台推出 Pro API 商业化服务
Mysql 身份认证绕过漏洞(CVE-2012-2122)
TDengine 社区问题双周精选 | 第二期
Detailed explanation of ThreadLocal
[compilation principle] LR (0) analyzer half done
Dockermysql modifies the root account password and grants permissions
Is "applet container technology" a gimmick or a new outlet?
浅谈网络安全之文件上传
石墨文档:4大对策解决企业文件信息安全问题
Puppeter connects to the existing Chrome browser
AcWing 4300. Two operations (minimum number of BFS searches)
POJ 1094 sorting it all out