python自动更新chromedriver

python自动化过程中,经常遇到脚本跑着跑着,就报错,一看,浏览器自动升级了。
共两张解决方案:
1、禁止浏览器自动升级
2、当脚本运行前先去检测当前的chromedriver与浏览器是否匹配,不匹配,就下载,然后将下载的chromedriver放置到指定位置。
本篇主要是记录方案2的实现,主要依靠webdriver_manager库来实现,代码如下:

import os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import shutil

"""
    使用须知:
    1.安装webdriver_manager库
        pip install webdriver_manager -i https://pypi.tuna.tsinghua.edu.cn/simple
"""


def update_chrome_driver(path) -> webdriver:
    """
    :param path: 下载后的chromedriver存放位置
    :return:
    """
    try:
        wb = webdriver.Chrome()
        print("当前已是最新的chromedriver")
        wb.quit()
    except Exception as e:
        print("更新驱动中……")
        driver_path = ChromeDriverManager().install()
        start = driver_path.rindex('/')
        src_path = driver_path[:start + 1]
        print(f"下载的路径:{src_path}")
        copy_dirs(src_path, path)
        print("===========更新驱动完成============")


def copy_dirs(src_path, target_path):
    '''
    :param src_path:
    :param target_path:
    :return:
    '''
    file_count = 0
    source_path = os.path.abspath(src_path)
    target_path = os.path.abspath(target_path)
    if not os.path.exists(target_path):
        os.makedirs(target_path)
    if os.path.exists(source_path):
        for root, dirs, files in os.walk(source_path):
            for file in files:
                src_file = os.path.join(root, file)
                shutil.copy(src_file, target_path)
                file_count += 1
                print(f"=====移动的文件========>{src_file}")
    return int(file_count)


if __name__ == '__main__':
    use_path = "你想要存放chromedriver的路径"
    update_chrome_driver(use_path)

以后每次执行脚本前,执行改文件即可,已经在mac和windows环境下验证过。
还有一点需要注意,use_path的路径是否有写入的权限!
mac电脑可以看一下这篇文章: macOs修改文件目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值