• python selenium下载一个合适的chromedriver.exe(稳定版本)


    可以使用该脚本来进行下载:
    下载前需要安装如下的依赖

    requests==2.27.1
    selenium==4.14.0
    webdriver_manager==4.0.1
    
    • 1
    • 2
    • 3

    下载脚本代码:

    import json
    import subprocess
    import shutil
    import os
    import time
    import zipfile
    
    import requests
    from webdriver_manager.core.os_manager import OperationSystemManager
    from webdriver_manager.chrome import ChromeDriverManager, ChromeType
    
    __all__ = {
        'download_suit_chrome_driver'
    }
    
    # 记录固定数据
    chrome_json_file = 'chrome_version.json'
    chrome_zip = 'chrome_driver.zip'
    
    
    def format_float(num):
        return '{:.2f}'.format(num)
    
    
    def download_file(name, url):
        '''
        :param name:下载保存的名称
        :param url: 下载链接
        :return:
        '''
        headers = {'Proxy-Connection': 'keep-alive'}
        r = requests.get(url, stream=True, headers=headers)
        length = float(r.headers['content-length'])
        f = open(name, 'wb')
        count = 0
        count_tmp = 0
        time1 = time.time()
        for chunk in r.iter_content(chunk_size=512):
            if chunk:
                f.write(chunk)
                count += len(chunk)
                if time.time() - time1 > 2:
                    p = count / length * 100
                    speed = (count - count_tmp) / 1024 / 1024 / 2
                    count_tmp = count
                    print(name + ': ' + format_float(p) + '%' + ' Speed: ' + format_float(speed) + 'M/S')
                    time1 = time.time()
        f.close()
    
    
    def install_chrome_driver():
        """
        安装chrome浏览器
        """
        try:
            p = ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()
            os.environ['CHROME_DRIVER_PATH'] = p
        except Exception as e:
            print("error")
    
    
    def get_chromedriver_version(chromedriver_path="chromedriver.exe"):
        """
        获取chrome_driver版本
        Args:
            chromedriver_path:
    
        Returns:
    
        """
        try:
            # 运行Chromedriver,并通过命令行参数获取版本信息
            result = subprocess.run([chromedriver_path, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
            if result.returncode == 0:
                # 如果成功执行,解析版本信息
                version = result.stdout.strip()
                version_list = str(version).split(" ")
                if len(version_list) == 3:
                    version = version_list[1]
                return True, version
            else:
                # 如果执行失败,输出错误信息
                error_message = result.stderr.strip()
                return False, f"Error: {error_message}"
        except Exception as e:
            return False, f"An error occurred: {str(e)}"
    
    
    def get_chrome_version():
        """
        获取chrome版本
        Returns:
        """
        try:
            os_version = OperationSystemManager().get_browser_version_from_os("google-chrome")
            print(f"os_version:{os_version}")
            return os_version
        except Exception as e:
            return None
    
    
    def get_chrome_version_info(version_info: str):
        if os.path.exists(chrome_json_file):
            with open(chrome_json_file) as f:
                data = f.read()
                json_data = json.loads(data)
                if json_data.get(version_info, None) is not None:
                    return True, json_data.get(version_info)
                else:
                    dict_version_info = {}
                    google_driver_json_url = 'https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json'
                    res = requests.get(google_driver_json_url)
                    res_dict = json.loads(res.text)
                    version_list = res_dict['versions']
                    for version in version_list:
                        downloads_ = version['downloads']
                        if downloads_.get('chromedriver', None) is not None:
                            download_list = downloads_['chromedriver']
                            for data in download_list:
                                if data['platform'] == 'win64':
                                    version_place = str(version['version'])
                                    version_ = version_place[0:version_place.rfind('.')]
                                    dict_version_info[version_] = data['url']
                    with open(chrome_json_file, 'w+') as f:
                        json.dump(dict_version_info, f, indent=4)
                    if dict_version_info.get(version_info, None) is not None:
                        version_url = dict_version_info[version_info]
                        return True, version_url
                    return False, 'error to get'
    
        else:
            dict_version_info = {}
            google_driver_json_url = 'https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json'
            res = requests.get(google_driver_json_url)
            res_dict = json.loads(res.text)
            version_list = res_dict['versions']
            for version in version_list:
                downloads_ = version['downloads']
                if downloads_.get('chromedriver', None) is not None:
                    download_list = downloads_['chromedriver']
                    for data in download_list:
                        if data['platform'] == 'win64':
                            version_place = version['version']
                            version_ = version_place[0:version_place.rfind('.')]
                            dict_version_info[version_] = data['url']
            with open(chrome_json_file, 'w+') as f:
                json.dump(dict_version_info, f, indent=4)
            if dict_version_info.get(version_info, None) is not None:
                version_url = dict_version_info[version_info]
                return True, version_url
            return False, 'error to get'
    
    
    def download_suit_chrome_driver(chrome_driver_path: str = "chromedriver.exe"):
        """
        下载合适的chrome_driver.exe
        Returns:
        """
        is_ok, chrome_driver_version = get_chromedriver_version(chrome_driver_path)
        browser_version = get_chrome_version()
        if is_ok:
            if str(chrome_driver_version).count(browser_version) > 0:
                print(f"当前已是合适的chrome_driver:{chrome_driver_version}")
                return True
            else:
                chrome_driver_big_version = browser_version.split(".")[0]
                if int(chrome_driver_big_version) < 115:
                    print("下载Chrome-Driver")
                    install_chrome_driver()
                else:
                    is_get_chrome, version_info = get_chrome_version_info(browser_version)
                    if is_get_chrome:
                        download_url = version_info
                        print('ok-remove-0')
                        if os.path.exists(chrome_zip):
                            os.remove(chrome_zip)
                        print('ok-remove-2')
                        download_file(chrome_zip, download_url)
                        print('ok-remove-3')
                        with zipfile.ZipFile(chrome_zip, 'r') as zip_ref:
                            zip_ref.extractall('./')
                        shutil.move('./chromedriver-win64/chromedriver.exe', './chromedriver.exe')
                        if os.path.exists(chrome_zip):
                            os.remove(chrome_zip)
        else:
            chrome_driver_big_version = browser_version.split(".")[0]
            if int(chrome_driver_big_version) < 115:
                print("下载Chrome-Driver")
                install_chrome_driver()
            else:
                is_get_chrome, version_info = get_chrome_version_info(browser_version)
                if is_get_chrome:
                    download_url = version_info
                    print('ok-remove-0')
                    if os.path.exists(chrome_zip):
                        os.remove(chrome_zip)
                    print('ok-remove-2')
                    download_file(chrome_zip, download_url)
                    print('ok-remove-3')
                    with zipfile.ZipFile(chrome_zip, 'r') as zip_ref:
                        zip_ref.extractall('./')
                    shutil.move('./chromedriver-win64/chromedriver.exe', './chromedriver.exe')
                    if os.path.exists(chrome_zip):
                        os.remove(chrome_zip)
    
    
    if __name__ == '__main__':
        download_suit_chrome_driver("chromedriver.exe")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210

    调用方式:

      download_suit_chrome_driver("xxxxx")  ## xxxxxx表示chrome_driver.exe路径(可为空)
    
    • 1

    github下载链接: https://github.com/huifeng-kooboo/download_chrome_driver

  • 相关阅读:
    Oracle实现把B表某一字段更新到A表
    MySQL-MySQL数据类型
    测试/开发程序员值这么多钱么?“我“不会愿赌服输......
    OpenCV 颜色检测| color detection
    【数据结构】栈的顺序表实现
    数组去重方法总结(记录)
    安卓无源码的情况下,替换广告
    2022年度收单外包机构评级预公示,评为D、E级机构如何进行异议申请
    2021秋招-总目录
    环印国际学校(GIIS)IB成绩38.6分,有什么秘密?
  • 原文地址:https://blog.csdn.net/Giser_D/article/details/133814392