Selenium Chrome 又又又自动更新了,是时候自动下载 driver 了

测试游记 · 2022年07月12日 · 最后由 西学东渐 回复于 2022年10月22日 · 6460 次阅读

在进行 UI 自动化的时候,需要下载对应的 driver 来控制浏览器,下面参考 seleniumbase 实现一个下载指定版本 chromedriver

查看 seleniumbase 中下载 chromedriver 的操作

seleniumbase.console_scripts.main中实现了driver文件的下载

它的用法为

sbase get chromedriver 101
sbase get chromedriver 101.0.4951.41
sbase get chromedriver latest-1
sbase get edgedriver 101.0.1210.32

步骤为:

  1. 获取当前操作系统
  2. 根据操作系统获取要下载的 driver 文件
  3. 根据文件名 + 版本信息拼接下载路径
  4. 下载到指定位置并解压

获取当前操作系统

使用platform模块可以获取到当前操作系统

方法为:platform.system()

根据操作系统确定指定 driver 名称

下载的位置TOOL_PATH可根据实际情况修改

import os
import platform

TOOL_PATH = "/Users/zhongxin/gitproject/wytest/src/tools"

class DriverOperator:
    def __init__(self):
        self.system = platform.system()
        if self.system == "Windows":
            self.path = f'{TOOL_PATH}/driver/win'
            self.chrome_file_name = "chromedriver_win32.zip"
        elif self.system == "Linux":
            self.path = f'{TOOL_PATH}/driver/linux'
            self.chrome_file_name = "chromedriver_linux64.zip"
        elif self.system == "Darwin":
            self.path = f'{TOOL_PATH}/driver/mac'
            self.chrome_file_name = "chromedriver_mac64.zip"
        else:
            raise Exception("未适配当前操作系统")

获取最新版本 Chromedriver

  1. 访问https://chromedriver.storage.googleapis.com/LATEST_RELEASE可以拿到当前最新的 driver 对象版本
  2. 访问https://chromedriver.storage.googleapis.com/LATEST_RELEASE_101可以拿到当前大版本 101 下的最新的 driver 对象版本

拼接获取版本地址

last = "https://chromedriver.storage.googleapis.com/LATEST_RELEASE"
version = version or requests.get(last).text
if len(version) < 4 and version.isdigit() and int(version) > 69:
    version = requests.get(f"{last}_{version}").text

下载并解压

在国内镜像处下载 Chromedriver 可以提升速度

download_url = f"https://registry.npmmirror.com/-/binary/chromedriver/{version}/{self.chrome_file_name}"
remote_file = requests.get(download_url)
file_path = os.path.join(self.path, self.chrome_file_name)
with open(file_path, "wb") as file:
    file.write(remote_file.content)

删除路径下旧的 driver,解压新 driver 到指定文件

zip_ref = zipfile.ZipFile(file_path, "r")
contents = zip_ref.namelist()
new_file = ""
if len(contents) == 1:
    f_name = contents[0]
    new_file = os.path.join(self.path, str(f_name))
    if os.path.exists(new_file):
        os.remove(new_file)
    zip_ref.extractall(self.path)
    zip_ref.close()
    os.remove(file_path)
    os.system(f"chmod -R 777 {new_file}")
return new_file

完整代码

# -*- coding: utf-8 -*-
# @Time    : 2022/7/11 17:44
# @Author  : zhongxin
# @Email   : 490336534@qq.com
# @File    : driveroperator.py
import os
import platform
import zipfile

import requests

from src.utils.constant import TOOL_PATH


class DriverOperator:
    def __init__(self):
        self.system = platform.system()
        if self.system == "Windows":
            self.path = f'{TOOL_PATH}/driver/win'
            self.chrome_file_name = "chromedriver_win32.zip"
        elif self.system == "Linux":
            self.path = f'{TOOL_PATH}/driver/linux'
            self.chrome_file_name = "chromedriver_linux64.zip"
        elif self.system == "Darwin":
            self.path = f'{TOOL_PATH}/driver/mac'
            self.chrome_file_name = "chromedriver_mac64.zip"
        else:
            raise Exception("未适配当前操作系统")

    def chrome_driver(self, version=None):
        """
        下载ChromeDriver
        @param version: 完整版本或者大版本号,不传入则下载最新版本
            例如:
                * 103.0.5060.53
                * 103
        @return:
        """
        last = "https://chromedriver.storage.googleapis.com/LATEST_RELEASE"
        version = version or requests.get(last).text
        if len(version) < 4 and version.isdigit() and int(version) > 69:
            version = requests.get(f"{last}_{version}").text
        download_url = f"https://registry.npmmirror.com/-/binary/chromedriver/{version}/{self.chrome_file_name}"
        remote_file = requests.get(download_url)
        file_path = os.path.join(self.path, self.chrome_file_name)
        with open(file_path, "wb") as file:
            file.write(remote_file.content)
        zip_ref = zipfile.ZipFile(file_path, "r")
        contents = zip_ref.namelist()
        new_file = ""
        if len(contents) == 1:
            f_name = contents[0]
            new_file = os.path.join(self.path, str(f_name))
            if os.path.exists(new_file):
                os.remove(new_file)
            zip_ref.extractall(self.path)
            zip_ref.close()
            os.remove(file_path)
            os.system(f"chmod -R 777 {new_file}")
        return new_file


测试

d = DriverOperator()
new_file = d.chrome_driver()
from selenium import webdriver

driver = webdriver.Chrome(executable_path=new_file)
print(driver.capabilities["browserVersion"])  # 当前浏览器版本
print(driver.capabilities["chrome"]["chromedriverVersion"])  # 当前driver版本
共收到 11 条回复 时间 点赞

用容器环境 不需要考虑这些东西 要什么版本就用什么版本的镜像

树叶 回复

恕我直言,比你那个科学多了😂

fiskeryang 回复

赞同

JoyMao 回复

同意按具体的浏览器版本来选择对应的 driver,不过我觉得可以这么优化:

  1. 起个定时任务去查询有没有新的版本,有的话下载下来。
  2. 所有的 driver 按版本号来解压存储,比如 driver100,driver101。
  3. 启动测试的时候,根据当前 Chrome 的版本来选择对应的 driver。
  4. 如果对存储空间敏感,可以考虑保留最近几个版本的 driver.
JoyMao 回复

https://www.jianshu.com/p/ffdfb6c7cbea,这个源码就是依照你的思路做的

酷火 回复

嗯,这个是常见思路。
其实可以用@jerrylizilong的方法,提前下好一些版本备用。因为 “墙” 的原因,chrome 更新和 driver 下载不是那么方便

我都是登录节点机器去下载替换 driver,没办法代码能力弱,先收藏,希望有时间能实践😁

一个脚本多端运行时需要考虑到部分运行端的 chrome 还是老版本的情况:
所以建议是先获取到运行端的 chrome 的版本号(大版本号,比如 103.1.201 就是 103),然后去判断是否有满足版本的 driver,没有的话再去下载。
比如 windows 端的 chrome 版本号可以从注册表中获取reg query "HKCU\Software\Google\Chrome\BLBeacon" /v Version

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册