本文主要是介绍开发一个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以上版本谷歌游览器自动下载驱动的库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!