在进行 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版本


↙↙↙阅读原文可查看相关链接,并与作者交流