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
"""defupdate_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("===========更新驱动完成============")defcopy_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)ifnot os.path.exists(target_path):
os.makedirs(target_path)if os.path.exists(source_path):for root, dirs, files in os.walk(source_path):forfilein files:
src_file = os.path.join(root,file)
shutil.copy(src_file, target_path)
file_count +=1print(f"=====移动的文件========>{src_file}")returnint(file_count)if __name__ =='__main__':
use_path ="你想要存放chromedriver的路径"
update_chrome_driver(use_path)
以后每次执行脚本前,执行改文件即可,已经在mac和windows环境下验证过。
还有一点需要注意,use_path的路径是否有写入的权限!
mac电脑可以看一下这篇文章: macOs修改文件目录
版权归原作者 u010799534 所有, 如有侵权,请联系我们删除。