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

编程入门 行业动态 更新时间:2024-10-20 05:35:17

开发一个115以上<a href=https://www.elefans.com/category/jswz/34/1771446.html style=版本谷歌游览器自动下载驱动的库"/>

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

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

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

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

但是自从115以上的谷歌游览器之后,以上方案全部失效,详见:

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.

基于此,我们除了可以手动去,还可以自己开发自动下载驱动的工具。

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

pip install UpdateChromeDriver --index-url / -U

库的简要说明可见:/

核心原理:首先通过命令或注册表获取谷歌游览器的版本,然后分析当前操作系统的平台,然后到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"""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 = streammunicate()[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 = ".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"""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"""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"""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以上版本谷歌游览器自动下载驱动的库

本文发布于:2023-11-17 13:21:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:版本   游览器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!