开发一个115以上版本谷歌游览器自动下载驱动的库

2023-11-03 13:52

本文主要是介绍开发一个115以上版本谷歌游览器自动下载驱动的库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在114版本以前,我给出了两个自动更新Selenium驱动的方案:

https://blog.csdn.net/as604049322/article/details/125540557

分别是自己写代码和使用ChromeDriverManager。

后面selenium升级到4.0以上版本后,selenium在环境变量中找不到目标驱动时也能使用SeleniumManager自动下载驱动。

但是自从115以上的谷歌游览器之后,以上方案全部失效,详见:https://chromedriver.chromium.org/downloads

If you are using Chrome version 115 or newer, please consult the Chrome for Testing availability dashboard. This page provides convenient JSON endpoints for specific ChromeDriver version downloading.

基于此,我们除了可以手动去https://googlechromelabs.github.io/chrome-for-testing/寻找对应驱动下载,还可以自己开发自动下载驱动的工具。

目前我以将其打包为库,使用以下命令即可安装:

pip install UpdateChromeDriver --index-url https://pypi.org/simple/ -U

库的简要说明可见:https://pypi.org/project/UpdateChromeDriver/

核心原理:首先通过命令或注册表获取谷歌游览器的版本,然后分析当前操作系统的平台,然后到json点查找匹配的下载点,最终下载到~\.cache\selenium,解压并移动到压缩包所在位置 ,最终创建对象并返回。

其他功能

获取当前操作系统的平台:

from UpdateChromeDriver import os_type
print(os_type())

获取当前谷歌游览器的版本:

from UpdateChromeDriver import get_browser_version_from_os
print(get_browser_version_from_os())

核心源码如下:

def linux_browser_apps_to_cmd() -> str:"""获取以下类似的命令的结果:google-chrome --version || google-chrome-stable --version"""apps = ("google-chrome", "google-chrome-stable","google-chrome-beta", "google-chrome-dev")ignore_errors_cmd_part = " 2>/dev/null" if os.getenv("WDM_LOG_LEVEL") == "0" else ""return " || ".join(f"{i} --version{ignore_errors_cmd_part}" for i in apps)def window_get_browser_version():"""代码作者:小小明-代码实体 xxmdmst.blog.csdn.net"""import winregtry:key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r"SOFTWARE\Google\Chrome\BLBeacon")version, _ = winreg.QueryValueEx(key, "version")winreg.CloseKey(key)return versionexcept:passtry:key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome")version, _ = winreg.QueryValueEx(key, "version")winreg.CloseKey(key)return versionexcept:passdef read_version_from_cmd(cmd):with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,stdin=subprocess.DEVNULL, shell=True) as stream:stdout = stream.communicate()[0].decode()return stdoutdef get_browser_version_from_os():pl = sys.platformtry:if pl == "linux" or pl == "linux2":cmd = linux_browser_apps_to_cmd()version = read_version_from_cmd(cmd)elif pl == "darwin":cmd = r"/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version"version = read_version_from_cmd(cmd)elif pl == "win32":version = window_get_browser_version()else:return Noneversion = re.search(r"\d+\.\d+\.\d+", version)return version.group(0) if version else Noneexcept Exception as e:return Nonedef os_type():pl = sys.platformarchitecture = platform.machine().lower()if pl == "darwin":if architecture == "x86_64":architecture = "x64"return f"mac-{architecture}"pl = re.search("[a-z]+", pl).group(0)architecture = 64 if architecture.endswith("64") else 32return f"{pl}{architecture}"def get_chromedriver_url(version):chrome_url = "https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json"res = requests.get(chrome_url)os_type_str = os_type()for obj in reversed(res.json()["versions"]):if obj["version"].startswith(version):for downloads in obj["downloads"]["chromedriver"]:if downloads["platform"] == os_type_str:return obj["version"], downloads["url"]breakdef show_download_progress(response, _bytes_threshold=100):"""代码作者:小小明-代码实体 xxmdmst.blog.csdn.net"""total = int(response.headers.get("Content-Length", 0))if total > _bytes_threshold:content = bytearray()progress_bar = tqdm(desc="[WDM] - Downloading", total=total,unit_scale=True, unit_divisor=1024, unit="B")for chunk in response.iter_content(chunk_size=8192):if chunk:progress_bar.update(len(chunk))content.extend(chunk)progress_bar.close()response._content = contentdef install_new_driver():"""代码作者:小小明-代码实体 xxmdmst.blog.csdn.net"""version = get_browser_version_from_os()print(f"谷歌游览器版本:{version}")driver_version, url = get_chromedriver_url(version)filename = url[url.rfind("/") + 1:]filename, ext = os.path.splitext(filename)selenium_dir = os.path.join(os.path.expanduser("~"), ".cache", "selenium")os.makedirs(selenium_dir, exist_ok=True)file = f"{selenium_dir}/{filename}_v{driver_version}{ext}"if os.path.exists(file):print(file, "已存在,跳过下载~")else:resp = requests.get(url, stream=True)show_download_progress(resp)with open(file, 'wb') as f:f.write(resp._content)suffix = ".exe" if sys.platform == "win32" else ""with zipfile.ZipFile(file) as zf:for name in zf.namelist():if name.endswith("chromedriver" + suffix) and "LICENSE.chromedriver" not in name:zf.extract(name, selenium_dir)print(name, "已解压到", selenium_dir)breaksrc = os.path.join(selenium_dir, name)dest = os.path.join(selenium_dir, os.path.basename(name))if src != dest:if os.path.exists(dest):os.remove(dest)os.rename(src, dest)print("已从", src, "移动到", dest)return destdef getChromeBrowser(options=None):"""代码作者:小小明-代码实体 xxmdmst.blog.csdn.net"""suffix = ".exe" if sys.platform == "win32" else ""executable_path = "chromedriver" + suffixselenium_dir = os.path.join(os.path.expanduser("~"), ".cache", "selenium")executable_path = os.path.join(selenium_dir, executable_path)service = Service(executable_path=executable_path)if not os.path.exists(executable_path):# 如果chromedriver不存在则直接升级install_new_driver()driver = webdriver.Chrome(options=options, service=service)return drivertry:driver = webdriver.Chrome(options=options, service=service)return driverexcept WebDriverException as e:install_new_driver()print(e)driver = webdriver.Chrome(options=options, service=service)return driver

这篇关于开发一个115以上版本谷歌游览器自动下载驱动的库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/338622

相关文章

Ubuntu如何升级Python版本

《Ubuntu如何升级Python版本》Ubuntu22.04Docker中,安装Python3.11后,使用update-alternatives设置为默认版本,最后用python3-V验证... 目China编程录问题描述前提环境解决方法总结问题描述Ubuntu22.04系统自带python3.10,想升级

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

基于Redis自动过期的流处理暂停机制

《基于Redis自动过期的流处理暂停机制》基于Redis自动过期的流处理暂停机制是一种高效、可靠且易于实现的解决方案,防止延时过大的数据影响实时处理自动恢复处理,以避免积压的数据影响实时性,下面就来详... 目录核心思路代码实现1. 初始化Redis连接和键前缀2. 接收数据时检查暂停状态3. 检测到延时过

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

Python开发简易网络服务器的示例详解(新手入门)

《Python开发简易网络服务器的示例详解(新手入门)》网络服务器是互联网基础设施的核心组件,它本质上是一个持续运行的程序,负责监听特定端口,本文将使用Python开发一个简单的网络服务器,感兴趣的小... 目录网络服务器基础概念python内置服务器模块1. HTTP服务器模块2. Socket服务器模块

更改linux系统的默认Python版本方式

《更改linux系统的默认Python版本方式》通过删除原Python软链接并创建指向python3.6的新链接,可切换系统默认Python版本,需注意版本冲突、环境混乱及维护问题,建议使用pyenv... 目录更改系统的默认python版本软链接软链接的特点创建软链接的命令使用场景注意事项总结更改系统的默

Linux升级或者切换python版本实现方式

《Linux升级或者切换python版本实现方式》本文介绍在Ubuntu/Debian系统升级Python至3.11或更高版本的方法,通过查看版本列表并选择新版本进行全局修改,需注意自动与手动模式的选... 目录升级系统python版本 (适用于全局修改)对于Ubuntu/Debian系统安装后,验证Pyt

Java 与 LibreOffice 集成开发指南(环境搭建及代码示例)

《Java与LibreOffice集成开发指南(环境搭建及代码示例)》本文介绍Java与LibreOffice的集成方法,涵盖环境配置、API调用、文档转换、UNO桥接及REST接口等技术,提供... 目录1. 引言2. 环境搭建2.1 安装 LibreOffice2.2 配置 Java 开发环境2.3 配