python selenium自动化之chrome与chromedriver版本兼容问题

在我们使用python+selenium来驱动chrome浏览器时,需要有chromedriver的支持,但是chrome浏览器更新比较频繁,而chrome浏览器和chromedriver则需要保持版本一致(版本一般相差1以内),此时我们就需要手动下载chromedriver来匹配此时的浏览器,但是生产环境操作比较麻烦。此时,我们就想是不是有一个程序来代替我们完成这个工作呢?

思路
比较当前的chrome浏览器版本号与chromedriver浏览号
如果不匹配,则下载一个新的chromedriver替换掉原来的
否则不进行任何操作

chrome的版本,我们一般通过浏览器地址栏输入“chrome://settings/help”来查看:
在这里插入图片描述

1.读取chrome浏览器版本信息

读取文件产品版本信息(需要提前安装pywin32模块),返回值是一个版本号的字符串:“ 89.0.4389.90”:

from win32com.client import Dispatch
allInfo=Dispatch("Scripting.FileSystemObject")
version = allInfo.GetFileVersion(r"D:\util\Google\Chrome\Application\chrome.exe")

我们也可以通过注册表的方式来获取chrome的版本号:

import winreg
def get_Chrome_version():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
    version, types = winreg.QueryValueEx(key, 'version')
    return version

2.读取chromedriver版本信息

我们在cmd里,CD到chromedriver所在目录,使用命令 .\chromedriver.exe --V 得到版本号并返回结果:ChromeDriver 89.0.4389.23 (61b08ee2c50024bab004e48d2b1b083cdbdac579-refs/branch-heads/4389@{#294}) ,该字符串按照空格符进行分段,第二段就是我们要的版本信息了。在python中,我们又该如何去跟终端交互拿到这个chromedriver版本号呢,其实很简单:

import os
def get_version():
    '''查询系统内的Chromedriver版本'''
    outstd = os.popen('chromedriver --version').read()
    return outstd.split(' ')[1]

chromedriver的下载地址
在这里插入图片描述

下载路径(URL)诸如:“http://npm.taobao.org/mirrors/chromedriver/89.0.4389.23/”,这用requests库就可以轻松实现这一需求:

import requests
def download_driver(download_url):
    '''下载文件'''
    file = requests.get(download_url)
    with open("chromedriver.zip", 'wb') as zip_file:        # 保存文件到脚本所在目录
        zip_file.write(file.content)
        print('下载成功')

你也可以指定完整路径,让下载的chromedriver.zip文件放到指定目录。

3.自动解压zip文件

加下来我们定义一个方法来自动解压zip文件,拿到里面的chromedriver.exe文件并自动覆盖旧版本chrome driver:

import zipfile
def unzip_driver(path):
    '''解压Chromedriver压缩包到指定目录'''
    f = zipfile.ZipFile("chromedriver.zip",'r')
    for file in f.namelist():
        f.extract(file, path)

4.下面是完整程序,可以直接做成工具直接调用

# -*- coding:utf-8 -*-

import requests,winreg,zipfile,re,os

url='http://npm.taobao.org/mirrors/chromedriver/' # chromedriver download link

def get_Chrome_version():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
    version, types = winreg.QueryValueEx(key, 'version')
    return version

def get_latest_version(url):
    '''查询最新的Chromedriver版本'''
    rep = requests.get(url).text
    time_list = []                                          # 用来存放版本时间
    time_version_dict = {}                                  # 用来存放版本与时间对应关系
    result = re.compile(r'\d.*?/</a>.*?Z').findall(rep)     # 匹配文件夹(版本号)和时间
    for i in result:
        time = i[-24:-1]                                    # 提取时间
        version = re.compile(r'.*?/').findall(i)[0]         # 提取版本号
        time_version_dict[time] = version                   # 构建时间和版本号的对应关系,形成字典
        time_list.append(time)                              # 形成时间列表
    latest_version = time_version_dict[max(time_list)][:-1] # 用最大(新)时间去字典中获取最新的版本号
    return latest_version
def get_server_chrome_versions():
    '''return all versions list'''
    versionList=[]
    url="http://npm.taobao.org/mirrors/chromedriver/"
    rep = requests.get(url).text
    result = re.compile(r'\d.*?/</a>.*?Z').findall(rep)
    for i in result:                                 # 提取时间
        version = re.compile(r'.*?/').findall(i)[0]         # 提取版本号
        versionList.append(version[:-1])                  # 将所有版本存入列表
    return versionList


def download_driver(download_url):
    '''下载文件'''
    file = requests.get(download_url)
    with open("chromedriver.zip", 'wb') as zip_file:        # 保存文件到脚本所在目录
        zip_file.write(file.content)
        print('下载成功')

def get_version():
    '''查询系统内的Chromedriver版本'''
    outstd = os.popen('chromedriver --version').read()
    return outstd.split(' ')[1]


def unzip_driver(path):
    '''解压Chromedriver压缩包到指定目录'''
    f = zipfile.ZipFile("chromedriver.zip",'r')
    for file in f.namelist():
        f.extract(file, path)

def get_path():
    outstd1 = os.popen('where chromedriver').read()
    fpath, fname = os.path.split(outstd1)
    return fpath

def check_update_chromedriver():
    chromeVersion=get_Chrome_version()
    chrome_main_version=int(chromeVersion.split(".")[0]) # chrome主版本号
    driverVersion=get_version()
    driver_main_version=int(driverVersion.split(".")[0]) # chromedriver主版本号
    download_url=""
    if driver_main_version!=chrome_main_version:
        print("chromedriver版本与chrome浏览器不兼容,更新中>>>")
        versionList=get_server_chrome_versions()
        if chromeVersion in versionList:
            download_url=f"{url}{chromeVersion}/chromedriver_win32.zip"
        else:
            for version in versionList:
                if version.startswith(str(chrome_main_version)):
                    download_url=f"{url}{version}/chromedriver_win32.zip"
                    break
            if download_url=="":
                print("暂无法找到与chrome兼容的chromedriver版本,请在http://npm.taobao.org/mirrors/chromedriver/ 核实。")

        download_driver(download_url=download_url)
        path = get_path()
        unzip_driver(path)
        os.remove("chromedriver.zip")
        print('更新后的Chromedriver版本为:', get_version())
    else:
       print("chromedriver版本与chrome浏览器相兼容,无需更新chromedriver版本!")

if __name__=="__main__":
    check_update_chromedriver()
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值