Python自动检测Chrome浏览器版本号并下载对应驱动文件[chromedriver.exe]

说明

实现原理是当使用的chromedriver.exe与当前Chrome浏览器版本不一致时会抛出异常,在异常信息中会包含当前Chrome版本信息和Chrome浏览器安装地址信息,通过捕获异常信息,正则匹配就可以过滤出Chrome版本号,然后再去官方动态下载对应版本的驱动并解压就可以了

  • 前提是需要内置一个chromedriver.exe,版本随便,不然抛出的是其他异常信息就获取不到版本号了

代码示例

import os
import re

import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from pypac import PACSession, get_pac
import os
import zipfile


def unzip_file(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 check_chrome_driver():
    # 获取项目根路径
    root_path = os.path.abspath(os.path.dirname(__file__)).replace("test", "")
    download_path = root_path + "download\\"  # 这里需要提前手动创建号download目录
    try:
        service = Service(root_path + "chromedriver.exe")
        driver = webdriver.Chrome(service=service)
    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",
                                                                                                             "")
        file_name = download_path + 'chromedriver_' + chrome_version + '.zip'
        print("Chrome Version:" + chrome_version)

        url = 'http://chromedriver.storage.googleapis.com/' + chrome_version + '/chromedriver_win32.zip'
        response = requests.get(url=url)

        # 使用代理
        # proxy = 'xxx.xxx.x.xx:8080'
        # proxies = {
        #     'http': 'http://' + proxy,
        #     'https': 'https://' + proxy
        # }
        # response = requests.get(url=url, proxies=proxies)

        # 使用PAC自动代理
        # pac = get_pac(url='http://xxx.xxx.x.xx:8080/xxx.pac')
        # pac_session = PACSession(pac)  # 解析pac文件
        # response = pac_session.get(url)

        # 保存ChromeDriver到当前项目路径下的/download目录下
        open(file_name, 'wb').write(response.content)
        # 解压zip文件
        unzip_file(file_name, download_path)


check_chrome_driver()

你可能感兴趣的:(Python,android,kotlin,java)