Loading... # python获取Chrome版本并更新匹配的chromedriver 在使用selenium库,经常会因为chromedriver的版本问题出现报错 ``` import re, zipfile, requests, os from selenium import webdriver from selenium.webdriver.chrome.service import Service class driver(object): def unzip_file(self, src_file, dest_dir, *password): if password: password = password.encode() zf = zipfile.ZipFile(src_file) try: zf.extractall(path=dest_dir, pwd=password) except RuntimeError as e: print(e) zf.close() def chrome_driver(self): root_path = os.path.abspath(os.path.dirname(__file__)).replace("test", "") # 获取项目根路径 i = 1 driver = None while (True): if i == 3: break try: service = Service(root_path + "\chromedriver.exe") options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') # 解决DevToolsActivePort文件不存在的报错 options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度 options.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败 driver = webdriver.Chrome(service=service, options=options) break except Exception as msg: print(1) reg = "Current browser version is.+with" chrome_version = re.search(reg, str(msg)).group().replace("Current browser version is ", "").replace( " with", "") file_path = root_path + '\catch\\' if not os.path.exists(file_path): os.makedirs(file_path) chrome_version_list = chrome_version.split('.') # print("Chrome Version:" + chrome_version) v3 = requests.get('http://chromedriver.storage.googleapis.com/').text.split( f'<Key>{chrome_version_list[0]}.{chrome_version_list[1]}.{chrome_version_list[2]}.', 1)[1].split( '/chromedriver_linux64.zip', 1)[0] file_name = 'chromedriver_' + chrome_version_list[0] + '_' + chrome_version_list[1] + '_' + \ chrome_version_list[2] + '_' + v3 + '.zip' downloadurl = 'http://chromedriver.storage.googleapis.com/' + chrome_version_list[0] + '.' + \ chrome_version_list[1] + '.' + chrome_version_list[ 2] + '.' + v3 + '/chromedriver_win32.zip' print(downloadurl) response = requests.get(downloadurl) # 保存ChromeDriver到当前项目路径下的/catch目录下 with open(file_path+file_name, 'wb') as f: f.write(response.content) # 解压zip文件 self.unzip_file(file_path+file_name, root_path) i += 1 return driver driver = driver().chrome_driver() driver.get('https://www.baidu.com') driver.quit() print(driver.page_source) ``` 最后修改:2022 年 04 月 28 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏