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

在进行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版本
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值