说明:Chrom自动更新后,对应的Chromedriver驱动也要手动下载更新,比较麻烦。这里的程序将根据单曲Chrome的版本将最新的驱动下载到本地。
import requests
import re
import os
import zipfile
import time
dPath = os.getcwd()
# 获取chrome版本
def get_chrome_version():
cmd = 'reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon" /v version'
cmdRes = os.popen(cmd).read() #执行命令拿到版本信息
cmdList = cmdRes.split(' ') #根据空格把拿到的信息转为列表
version = cmdList[len(cmdList)-1].replace('\n', '') #只要最后一个数据就是版本号,不要其他的信息
varsionList = version.split('.') #版本号更具.转为列表
varsionList.pop() #删除列表最后一个小版本号
varsionStr = ".".join(varsionList) #组装大版本号
return varsionStr
# 已有Chromedriver的版本
def get_fz_chromedriver_version():
cmd = dPath+'\chromedriver\chromedriver.exe -version'
cmdRes = os.popen(cmd).read() #执行命令拿到版本信息
cmdList = cmdRes.split(' ') #根据空格把拿到的信息转为列表
return cmdList[1]
def get_latest_version(url):
'''查询最新的Chromedriver版本'''
rep = requests.get(url).text
time_list = [] # 用来存放版本时间
time_version_dict = {} # 用来存放版本与时间对应关系
result = re.compile(r'\d.*?/</a>.*?Z').findall(rep) # 匹配文件夹(版本号)和时间
for i in result:
time = i[-24:-1] # 提取时间
version = re.compile(r'.*?/').findall(i)[0] # 提取版本号
time_version_dict[time] = version # 构建时间和版本号的对应关系,形成字典
time_list.append(time) # 形成时间列表
latest_version = time_version_dict[max(time_list)][:-1] # 用最大(新)时间去字典中获取最新的版本号
return latest_version
def download_driver(download_url):
'''下载文件'''
file = requests.get(download_url)
with open("chromedriver.zip", 'wb') as zip_file: # 保存文件到脚本所在目录
zip_file.write(file.content)
print('下载成功')
def get_version():
'''查询系统内的Chromedriver版本'''
outstd2 = os.popen('chromedriver --version').read()
return outstd2.split(' ')[1]
def get_path():
'''查询系统内Chromedriver的存放路径'''
return dPath+'\chromedriver\\'
# outstd1 = os.popen('where chromedriver').read()
# return outstd1.strip('chromedriver.exe\n')
def unzip_driver(path):
'''解压Chromedriver压缩包到指定目录'''
f = zipfile.ZipFile("chromedriver.zip",'r')
for file in f.namelist():
f.extract(file, path)
if __name__ == "__main__":
version = get_chrome_version() # 原来是get_version()
print('当前系统内的Chrome版本为:', version)
url = 'http://npm.taobao.org/mirrors/chromedriver/'
latest_version = get_latest_version(url)
print('最新的chromedriver版本为:', latest_version)
locaVersion = get_fz_chromedriver_version()
print('当前FZ的chromedriver版本为:', locaVersion)
if version not in latest_version:
print('当前系统内的Chrome和最新Chromedriver版本不匹配,不执行更新!')
else:
if locaVersion == latest_version:
print('已是最新版本,不执行更新!')
else:
print('当前系统内的Chrome和最新Chromedriver版本匹配,执行更新!')
download_url = url + latest_version + '/chromedriver_win32.zip' # 拼接下载链接
download_driver(download_url)
path = get_path()
print('替换路径为:', path)
unzip_driver(path)
print('更新后的Chromedriver版本为:', get_version())
time.sleep(3)