根据当前谷歌浏览器版本获取或更新更新chromedriver.exe

import os
import requests
from selenium import webdriver
import re
import zipfile


def un_zip(file_name_path, file_path):
    """unzip zip file"""
    folder_path = file_path + file_name_path.split('\\')[-1].split('.')[0]
    # 解压文件,创建一个zip_file对象
    zip_file = zipfile.ZipFile(file_name_path)
    try:
        if os.path.isdir(folder_path):
            None
        else:
            os.mkdir(folder_path)
        for names in zip_file.namelist():
            zip_file.extract(names, folder_path)
        print(file_name_path, '解压成功')
    except Exception as result:
        print("文件名重复,报错:\n%s\n请查看文件是否已解压" % result)


def get_chromedriver_state(path):
    try:
        chrome_options = webdriver.ChromeOptions()
        chromedriver_path = path + r'chromedriver_win32\\chromedriver.exe'
        webdriver.Chrome(executable_path=chromedriver_path, options=chrome_options)
        return {'state': '1', 'explain': '该版本可使用', 'path': path + r'chromedriver_win32\\chromedriver.exe'}
    except Exception as e:
        print('e:', e)
        if "'chromedriver.exe' executable needs to be in PATH" in str(e):
            print('未检到chromedriver.exe文件,开始下载旧版未检到chromedriver!')
            url = 'http://chromedriver.storage.googleapis.com/99.0.4844.35/chromedriver_win32.zip'
            r = requests.get(url).content
            open(path + 'chromedriver_win32.zip', 'wb+').write(r)
            un_zip(path + 'chromedriver_win32.zip', path)
            return get_chromedriver_state(path)
        version_number = re.findall(r'browser version is (.*) with binary', str(e))[0]
        print('检测到chrome版本为:', version_number)
        print('开始下载压缩文件到:', path)

    url = 'http://chromedriver.storage.googleapis.com/' + version_number + '/chromedriver_win32.zip'
    print('下载链接:', url)
    r = requests.get(url).content
    open(path + 'chromedriver_win32.zip', 'wb+').write(r)
    un_zip(path + 'chromedriver_win32.zip', path)
    return {'state': '1', 'explain': '文件已更新', 'path': path + r'chromedriver_win32\\chromedriver.exe'}


if __name__ == '__main__':
    print(get_chromedriver_state('cs\\'))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值