Chromedriver125以后的去哪找,以及自动更新Chromedriver的Python脚本

1. 查看Chrome浏览器的版本

点进这个网站查看:chrome://settings/help
在这里插入图片描述

2. 找到对应的chromedriver

此前的话,是去这个里面去找:https://chromedriver.storage.googleapis.com/index.html或者访问淘宝的镜像站点http://npm.taobao.org/mirrors/chromedriver/(国内网络访问这个会比较便捷快速,下载也快),可是现在这里面列出来最新版本的Chromedriver只对应到了 Chrome 114,最近几个月的版本都没有更新了。

然后,在https://stackoverflow.com/的一则问答中,看到有答主给出的Chromedriver团队GitHub上的仓库已经更新有Chromedriver的各版本下载链接https://googlechromelabs.github.io/chrome-for-testing/#stable。这里已经有了Chrome最新测试版本的Chrome 以及对应的Chromedriver可下载可用。

3. 安装ChromeDriver

就把刚刚下载的压缩包chromedriver-win64.zip解压存放在任意一个已经添加到系统环境变量PATH的文件夹就行,我的习惯是默认解压到Python目录下(因为Python目录本身就已经需要被设置为环境变量Path)

PS:怎么额外添加到环境变量,可行百度一哈~

4.一个Python脚本,用于自动访问github库、下载最新版本Win64版本Chromedriver,解压存放到Python根目录。

import os
import re
import sys
import winreg
import zipfile,time
from pathlib import Path
import shutil
import requests
CookiesName = "chrome_driver_update"
python_root = Path(sys.executable).parent  # python安装目录
socket.setdefaulttimeout(30)
version_re = re.compile(r'^[1-9]\d*\.\d*.\d*')  # 匹配前3位版本信息


def get_chrome_version():
    """通过注册表查询Chrome版本信息: HKEY_CURRENT_USER\SOFTWARE\Google\Chrome\BLBeacon: version"""
    try:
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'SOFTWARE\Google\Chrome\BLBeacon')
        value = winreg.QueryValueEx(key, 'version')[0]
        return version_re.findall(value)[0]
    except WindowsError as e:
        return '0.0.0'  # 没有安装Chrome浏览器


def get_chrome_driver_version():
    try:
        result = os.popen('chromedriver --version').read()
        version = result.split(' ')[1]
        return '.'.join(version.split('.')[:-1])
    except Exception as e:
        return '0.0.0'  # 没有安装ChromeDriver


def get_latest_chrome_driver(chrome_version):#使用淘宝镜像下载安装Chromedriver   2023年11月失效
    base_url = 'http://npm.taobao.org/mirrors/chromedriver/'  # chromedriver在国内的淘宝镜像网站
    url = f'{base_url}LATEST_RELEASE_{chrome_version}'
    latest_version = requests.get(url).text        
    download_url = f'{base_url}{latest_version}/chromedriver_win64.zip'        
    
    # 下载chromedriver zip文件到Python 根目录
    response = requests.get(download_url)    
    local_file = python_root / 'chromedriver.zip'
    with open(local_file, 'wb') as zip_file:
        zip_file.write(response.content)

    # 解压缩zip文件到python安装目录
    f = zipfile.ZipFile(local_file, 'r')
    for file in f.namelist():
        f.extract(file, python_root)
    f.close()

    local_file.unlink()  # 解压缩完成后删除zip文件
def get_chrome_driver_fromGithub(chrome_version):#使用github仓库上的Chromedriver
	#(2024-05-17更新软件逻辑,访问本链接查询最新state版本号系统都超时了,索性这一小节就不执行了也可以)
    try:
        base_url = f'https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_STABLE'
        latest_version = requests.get(base_url).text#查询最新的state版本号
        print(f"GitHub库里最新完整版driver = ]{latest_version}[")
    except BaseException as msg:
        print(f"查询在线最新version-station版本出错{msg}")
    
    #遍历所用可能可用的Chrome driver下载链接
    try:
        Look_url = f'https://googlechromelabs.github.io/chrome-for-testing/'
        driver = requests.get(Look_url).text
        #print(driver.text)        
        Links=[]
        codes = re.compile(r'<code>(.*?)</code>',re.S).findall(driver)
        for i in codes:
            link = re.compile(r'http(.*?)win64/chrome-win64.zip').findall(i)
            Links=Links+link
        # print(len(Links))
        # print(Links)
    except BaseException as msg:
        print(f"查询在线最新version-station版本出错{msg}")
        time.sleep(20)   
    else:
        for i in Links:
            download_url = f'http{download_url}win64/chrome-win64.zip'
            print(f"正在下载解压,预设定的超时时间为30秒,请耐性等待。或者可以复制链接人工处置。\n{download_url}")
            if download_chrome_driver_by_Request(download_url=download_url)==True:
                return True
        print(f"已在该网址找到如上几个链接,本脚本下载失败请人工复制链接地址自行访问该网址下载(2024-05-17 在更新125.0.6422时遇到该链接无法使用,最终人工反复几次使用Chrome浏览器访问该链接才成功下载下来。期间使用IDM、迅雷均无法下载。大概率是该网址的反爬虫策略做的比较极端了吧。Chrome的更新速度太快、频率高。所以本程序执行到这里会停留10000秒,请发现报错后人工复制链接安排下载):",end="\n\n\n")    
        print("如果前面没找到任何一个可用的下载链接,推荐访问如下网址,可能是下载链接的命名逻辑发生了变动,需要对应修改本程序的正则选择器规则")
        print("https://googlechromelabs.github.io/chrome-for-testing/")
        print(f"推荐解压缩替换地址【大部分人都会把python的根路径设置为系统PATH吧?如果你不是的话,就自己找一个系统Path解压存放Chromedriver.exe】<    ^ ~ ^   >:\n{python_root}/chromedriver.exe")
        time.sleep(1000)
        return False    

            
    get_chrome_driver_fromGithub(chrome_version)    
def download_chrome_driver_by_Request(download_url):    
    #逐一下载chromedriver zip文件到Python 根目录
    local_file = python_root / 'chromedriver.zip'
    
    try:
        response = requests.get(download_url,stream=True,allow_redirects=True)    
        with open(local_file, 'wb') as zip_file:
            zip_file.write(response.content)
        extract_zip(local_file)
    except BaseException as msg:
        print(f"下载{download_url}出错{msg}")
        return download_chrome_driver_by_urlopen(download_url,local_file)
    else:            
        return True

def download_chrome_driver_by_urlopen(download_url,local_file):
    try:
        import urllib.request
        import socket
        header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36 HBPC/12.1.3.306'}
        socket.setdefaulttimeout(30)#设置超时时间为20秒
        request=urllib.request.Request(download_url,headers=header)
        response = urllib.request.urlopen(request)
        with open(local_file, 'wb') as zip_file:
            zip_file.write(response.content)
        extract_zip(local_file)
    except BaseException as msg:
        print(f"下载{download_url}出错{msg}")   
        return False     
    else:
        return True
        
def extract_zip(local_file):
    try:
        # 解压缩zip文件到python安装目录
        f = zipfile.ZipFile(local_file, 'r')    
        f.extract('chromedriver-win64/chromedriver.exe', python_root)    
        f.close()
        local_file.unlink()  # 解压缩完成后删除zip文件

        # 从chromedriver-win64目录移动Chromedriver.exe 
        os.remove(f"{python_root}/chromedriver.exe")
        shutil.move(f"{python_root}/chromedriver-win64/chromedriver.exe",python_root)
    except BaseException as msg:
        print(f"解压缩本地文件时遇到错误{msg}")
        return False
    else:
        return True
def check_chrome_driver_update():
    chrome_version = get_chrome_version()
    driver_version = get_chrome_driver_version()
    print(f'chrome_version = {chrome_version},driver_version = {driver_version}')
    if chrome_version == driver_version:
        print('No need to update')
    else:
        try:
            get_chrome_driver_fromGithub(chrome_version)
        except Exception as e:
            print(f'GitHub仓库Fail to update: {e}')
            # try:
            #     get_latest_chrome_driver(chrome_version)
            # except Exception as e:
            #     print(f'淘宝镜像站Fail to update:{e}')
            # time.sleep(20)
        else:
            print("Success to download chrome_driver.")


if __name__ == '__main__':
    print(python_root)
    check_chrome_driver_update()

这个脚本我是添加到“任务程序计划”了,设为每天自动运行一次。实在是Chrome更新频率太高。。。

  • 48
    点赞
  • 125
    收藏
    觉得还不错? 一键收藏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值