自动检测下载ChromeDriver
作者:Rem ㅤ | 发布时间:
也许你也有Chrome不知不觉中升级与ChromeDriver版本不匹配的经历,此时再去下载对应版本的ChromeDriver是一件略微麻烦的事情,针对此问题我编写了一个小小的工具。
import os
import re
from selenium import webdriver
import requests
import json
import zipfile
import shutil
# python地址
pythonPath = r'D:\python'
ChromePath = r'C:\Program Files\Google\Chrome\Application'
# 获取chrom版本
def getVersiom():
try:
option = webdriver.ChromeOptions()
option.add_argument('--headless') # 无界面
webdriver.Chrome(options=option)
except Exception as msg:
print("ChromeWebDriver异常:" + str(msg))
reg = "Current browser version is.+with"
chrome_version = re.search(reg, str(msg)).group().replace(
"Current browser version is ", "").replace(" with", "")
print("Chrome Version:" + chrome_version)
return chrome_version[:-3]
return True
# 下载对应版本的chromeDriver
def download(Version):
url = 'https://registry.npmmirror.com/-/binary/chromedriver/'
response = requests.get(url, verify=False)
json_drivers = json.loads(response.text)
for data in json_drivers:
if data['name'][:-4] == Version:
url = data['url']
version = data['name'][:-1]
url += 'chromedriver_win32.zip'
down = requests.get(url)
filename = r'./' + 'chromedriver_' + version + '.zip'
savename = r'./'
open(file=filename, mode='wb').write(down.content)
# 解压文件
file = zipfile.ZipFile(filename)
file.extractall(savename)
file.close()
# 移动文件
os.remove(filename)
shutil.copy2(r'./chromedriver.exe', ChromePath)
shutil.copy2(r'./chromedriver.exe', pythonPath)
if os.path.exists(r'./LICENSE.chromedriver'):
os.remove(r'./LICENSE.chromedriver')
os.remove(r'./chromedriver.exe')
Version = getVersiom()
if Version is True:
print("chrmoeDriver版本正确")
else:
download(Version)
print("已载最新版")
原理:先下载到当前路径,然后复制到Chrome路径下和Python路径下,最后删除当前路径下的下载的文件。
标签:工具分享, 学习笔记