微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python selenium 自动更新浏览器驱动文件

说明
实现原理是当使用的chromedriver.exe与当前Chrome浏览器版本不一致时会抛出异常,

异常信息中会包含当前Chrome版本信息和Chrome浏览器安装地址信息,通过捕获异常信息

正则匹配就可以过滤出Chrome版本号,然后再去官方动态下载对应版本的驱动并解压就可以了

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

经过修改,即使当前版本的驱动没有更新也不会报错而是选择最新的驱动进行下载。

请自己替换文件路径

 

def get_browser():
    # 不加载图片和css
    chrome_options = webdriver.ChromeOptions()
    # 不显示浏览器窗口
    chrome_options.add_argument('headless')
    prefs = {"profile.managed_default_content_settings.images": 2, 'permissions.default.stylesheet': 2}
    chrome_options.add_experimental_option("prefs", prefs)
    try:
        driverobject = Service(r"D:\Program Files\chromedriver.exe")
        driver_ = Chrome(service=driverobject, options=chrome_options)
        driver_.get("http://baidu.com")
        return driver_
    # 驱动不匹配时自动更新
    except Exception as msg:
        print("浏览器驱动不匹配正在更新...")
        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)
        chrome_version_list = chrome_version.split(".")
        str_ = '.'
        del chrome_version_list[3]
        re_ = str_.join(chrome_version_list) + ".\d{2}"
        r = requests.get("http://chromedriver.storage.googleapis.com")
        chrome_version_list_2 = list(set(re.findall(re_, r.text)))
        chrome_version_list_2.sort()
        chrome_version = chrome_version_list_2[len(chrome_version_list_2) - 1]
        url = 'http://chromedriver.storage.googleapis.com/' + chrome_version + '/chromedriver_win32.zip'
        path = r"D:\Program Files\chromedriver_win32.zip"
        wget.download(url, path)
        with zipfile.ZipFile(r"D:\Program Files\chromedriver_win32.zip") as zf:
            zf.extractall(r"D:\Program Files")
        os.remove(r"D:\Program Files\chromedriver_win32.zip")
        driver_ = get_browser()

    return driver_

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐