问题是我做了一个分析数据生成图片的小工具,但是过一会截图就失效了,因为工具里的chromedirver和自动更新的chrome版本不匹配。解决方法由于用户不是一个人,非专业人士,不建议手动解决。自动更新更可靠。思路很简单:1、查询当前chrome版本2、查询当前chromedriver版本3、比较两者是否一致。如果不一致,更新chromedirver驱动代码和update函数相关包(摘自一堆代码,可能有漏的,自己安装)importosfrominit.Loggerimportlogimportre#regularimportwinreg#windowsregistryimportzipfile#压缩解压importrequests#下载chromedirver的镜像地址base_url='http://npm.taobao.org/mirrors/chromedriver/'#匹配前3个版本号的正则表达式version_re=re.compile(r'^[1-9]\d*\.\d*.\d*')#通过注册表查询chrome版本defgetChromeVersion():try:key=winreg.OpenKey(winreg.HKEY_CURRENT_USER,'Software\\Google\\Chrome\\BLBeacon')value,t=winreg.QueryValueEx(key,'version')returnversion_re.findall(value)[0]#返回除WindowsError之外版本号的前3位数字为e:#Chrome浏览器未安装return"1.1.1"#查询Chromedriver版本defgetChromeDriverVersion():outstd2=os.popen('chromedriver--version').read()try:version=outstd2.split('')[1]version=".".加入(version.split(".")[:-1])returnversionexceptExceptionase:return"0.0.0"#检查chromedirver是否更新defcheckChromeDriverUpdate():chrome_version=getChromeVersion()log.info(f'currentchromeversion:{chrome_version}')driver_version=getChromeDriverVersion()log.info(f'Currentchromedriverversion:{driver_version}')ifchrome_version==driver_version:log.info("版本兼容,无需更新。")返回日志。info("chromedriverversionisnotcompatiblewithchromebrowser,updating>>>")try:getLatestChromeDriver(chrome_version)log.info("chromedriverupdatesuccessfully!")exceptrequests.exceptions.Timeout:log.info("chromedriverdownloadFailed错误,pleasecheckthenetworkandtryagain!")exceptExceptionase:log.info(f"chromedriverupdatefailedforunknownreasons:{e}")#获取本chrome版本的最新驱动版本号defgetLatestChromeDriver(version):url=f"{base_url}LATEST_RELEASE_{version}"latest_version=requests.get(url).textprint(f"与当前chrome匹配的最新chromedriver版本是:{latest_version}")#下载chromedriverprint("开始下载chromedriver...")download_url=f"{base_url}{latest_version}/chromedriver_win32.zip"file=requests.get(download_url)withopen("chromedriver.zip",'wb')aszip_file:#将文件保存到脚本所在目录zip_file.write(file.content)print("下载完成。")#解压f=zipfile.ZipFile("chromedriver.zip",'r')对于f中的文件。namelist():f.extract(file)print("解压完成。")结果:兼容与否
