python 自动更新chromedriver.exe 插件

300 阅读3分钟

一、导入依赖

import os
import re
import shutil
import sys
import time
import winreg
import zipfile
from pathlib import Path

import requests
from tqdm import tqdm

二、直接操作

python_root = Path(sys.executable).parent  # python安装目录

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


# 使用淘宝镜像下载安装Chromedriver   2023年11月失效
def get_latest_chrome_driver(chrome_version):
    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文件
    del_file_or_dir(local_file, "file")


# 使用github仓库上的Chromedriver
def get_chrome_driver_fromGithub(chrome_version):
    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}")
    # download_url = f'https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/{latest_version}/win64/chromedriver-win64.zip'
    download_url = f'https://storage.googleapis.com/chrome-for-testing-public/{latest_version}/win64/chromedriver-win64.zip'
    # 下载chromedriver zip文件到Python 根目录
    response = requests.get(download_url)
    local_file = python_root / 'chromedriver.zip'
    total_size = int(response.headers.get('content-length', 0))
    with open(local_file, 'wb') as zip_file:
        for chunk in tqdm(response.iter_content(chunk_size=1024), total=total_size / 1024, unit='KB', unit_scale=True):
            zip_file.write(chunk)
        # zip_file.write(response.content)

    print("下载完成")
    # 解压缩zip文件到python安装目录
    f = zipfile.ZipFile(local_file, 'r')
    f.extract('chromedriver-win64/chromedriver.exe', python_root)
    f.close()

    print("解压完成")

    # local_file.unlink()  # 解压缩完成后删除zip文件
    # 从chromedriver-win64目录移动Chromedriver.exe
    # 删除原来的文件
    del_file_or_dir(f"{python_root}/chromedriver.exe", "file")
    shutil.move(f"{python_root}/chromedriver-win64/chromedriver.exe", python_root)
    print("移动完成")

    # 删除文件夹下的所有内容
    # 指定要删除的文件夹路径
    folder_path = f'{python_root}/chromedriver-win64'
    del_file_or_dir(folder_path, "dir")

    # 指定要删除的文件路径 -- 删除zip文件
    file_path = f'{python_root}/chromedriver.zip'
    del_file_or_dir(file_path, "file")


# 删除文件或文件夹的方法
def del_file_or_dir(file_path, path_type):
    if os.path.exists(file_path):
        if path_type == "file":
            os.remove(file_path)
            print(f"{file_path},文件删除成功")
        else:
            shutil.rmtree(file_path)
            print(f"{file_path},文件夹所有删除成功")
    else:
        print(f"{file_path} ==> 路径不存在")


# 检查更新
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')
        print("已经是最新版本不需要更新")
    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()

三、电脑创建自动化任务

image.png

image.png 设置运行时间,间隔,以及上面的程序就可以了

这样子再也不用手动去找对应的 chromedriver.exe 版本啦