当 Chrome 浏览器通过 Python selenium 自动更新时,如何使用特定版本的 ChromeDriver

2025-01-21 09:01:00
admin
原创
116
摘要:问题描述:我是 Selenium 的新手,现在我可以使用 selenium 和 Chromedriver 进行基本的自动测试,代码运行良好,但问题是 Chrome 浏览器总是在后端自动更新,而 Chrome 更新后代码总是无法运行。我知道我需要下载新的 chromedriver 来解决这个问题,但我想知道是否...

问题描述:

我是 Selenium 的新手,现在我可以使用 selenium 和 Chromedriver 进行基本的自动测试,代码运行良好,但问题是 Chrome 浏览器总是在后端自动更新,而 Chrome 更新后代码总是无法运行。我知道我需要下载新的 chromedriver 来解决这个问题,但我想知道是否有任何方法可以在不禁用 chromebrowser 更新的情况下解决这个问题?谢谢。

我正在使用 Windows 10 / Chrome 版本 67 / Python 3.6.4 / Selenium 3.12.0


解决方案 1:

不,除了更新ChromeDriver二进制版本之外没有其他选择,而Chrome 浏览器会继续自动更新。


原因

每个Chrome 浏览器都会在现有功能中添加、修改和删除某些功能后发布。为了符合当前的浏览器功能集,Chrome 团队会不时发布兼容的ChromeDriver二进制文件。这些ChromeDriver二进制文件能够与Chrome 浏览器交互。某些版本的ChromeDriver二进制文件支持特定范围的Chrome 浏览器版本(一些最新版本),如下所示:

  • ChromeDriver v 84.0.4147.30 (2020-05-28)

Supports Chrome version 84
  • ChromeDriver v 83.0.4103.39 (2020-05-05)

Supports Chrome version 83
  • ChromeDriver v 82被刻意跳过。

  • ChromeDriver v 81.0.4044.138 (2020-05-05)

Supports Chrome version 81
  • ChromeDriver v 80.0.3987.106 (2020-02-13)

Supports Chrome version 80
  • ChromeDriver v 79.0.3945.36 (2019-11-18)

Supports Chrome version 79
  • ChromeDriver v 78.0.3904.70 (2019-10-21)

Supports Chrome version 78
  • ChromeDriver v 77.0.3865.40 (2019-08-20)

Supports Chrome version 77
  • ChromeDriver v 76.0.3809.126 (2019-08-20)

Supports Chrome version 76
  • ChromeDriver v 75.0.3770.8(2019-04-29)

Supports Chrome version 75
  • ChromeDriver v 74.0.3729.6 (2019-03-14)

Supports Chrome version 74
  • ChromeDriver v 73.0.3683.68 (2019-03-06)

Supports Chrome version 73
  • ChromeDriver v 2.46(2019-02-01)

Supports Chrome v71-73
  • ChromeDriver v 2.45(2018-12-10)

Supports Chrome v70-72
  • ChromeDriver v 2.44(2018-11-19)

Supports Chrome v69-71
  • ChromeDriver v 2.43(2018-10-16)

Supports Chrome v69-71
  • ChromeDriver v 2.42(2018-09-13)

Supports Chrome v68-70
  • ChromeDriver v 2.41(2018-07-27)

Supports Chrome v67-69
  • ChromeDriver v 2.40(2018-06-07)

Supports Chrome v66-68
  • ChromeDriver v 2.39(2018-05-30)

Supports Chrome v66-68
  • ChromeDriver v 2.38(2018-04-17)

Supports Chrome v65-67
  • ChromeDriver v 2.37(2018-03-16)

Supports Chrome v64-66
  • ChromeDriver v 2.36(2018-03-02)

Supports Chrome v63-65
  • ChromeDriver v 2.35(2018-01-10)

Supports Chrome v62-64
  • ChromeDriver v 2.34(2017-12-10)

Supports Chrome v61-63
  • ChromeDriver v 2.33(2017-10-03)

Supports Chrome v60-62
  • ChromeDriver v 2.32(2017-08-30)

Supports Chrome v59-61
  • ChromeDriver v 2.31(2017-07-21)

Supports Chrome v58-60
  • ChromeDriver v 2.30(2017-06-07)

Supports Chrome v58-60
  • ChromeDriver v 2.29(2017-04-04)

Supports Chrome v56-58

结论

为了使您的脚本/程序与更新的Chrome 浏览器保持交互,您必须根据兼容性使ChromeDriver二进制文件的版本与Chrome 浏览器保持同步。

解决方案 2:

我正在使用这个对我有用的库。

https://pypi.org/project/chromedriver-autoinstaller/

项目描述

chromedriver-autoinstaller 自动下载并安装支持当前安装的 chrome 版本的 chromedriver。此安装程序支持 Linux、MacOS 和 Windows 操作系统。

安装

pip install chromedriver-autoinstaller

例子

from selenium import webdriver
import chromedriver_autoinstaller


chromedriver_autoinstaller.install()  # Check if the current version of chromedriver exists
                                      # and if it doesn't exist, download it automatically,
                                      # then add chromedriver to path

driver = webdriver.Chrome()
driver.get("http://www.python.org")
assert "Python" in driver.title

编辑。我​​也使用 @ATJ 评论的选项,但用于定义 chrome 的 binary_location() 而不是 CHROMEDRIVER_PATH。实际上,我喜欢这个扩展的一件事是不需要指定这个路径,因为它已经处理好了。在使用它之前,我曾经浪费时间放置路径,搜索它的位置,将驱动程序的副本放在项目文件夹或系统路径文件夹中。

我还用这个快速代码制作了一个模板来使用 selenium,我用它打开新文件然后继续:


import chromedriver_autoinstaller
from selenium import webdriver
chromedriver_autoinstaller.install()
options = webdriver.ChromeOptions()
options.binary_location = ('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe')
driver = webdriver.Chrome(options=options)


并且这个快速脚本在第一次使用新电脑时在终端上运行


import os
os.system("pip install  selenium ")
os.system("pip install  chromedriver_autoinstaller ")

-我的模板的实际完整版本(留下注释更快捷,减少重复工作,取消注释使其更无依赖性)


import chromedriver_autoinstaller
from selenium import webdriver
#from selenium.webdriver.common.keys import Keys
# import os
#    # to use when 1st time on the machine and then leave comented
# os.system("pip install  selenium ")
# os.system("pip install  chromedriver_autoinstaller ")
chromedriver_autoinstaller.install()
options = webdriver.ChromeOptions()
options.headless = False
options.binary_location = ('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe')
driver = webdriver.Chrome(options=options)

编辑。2-带有二进制位置的我的模板的实际完整版本。好吧。我刚刚用二进制位置测试了代码,它也能正常工作。好吧,不知道为什么它以前不起作用,这个位置是默认的,因此除非在安装 chrome 时更改了位置,否则不应更改。现在重新审视它是件好事,我刚刚为将来的所有用途保存了一行。


import chromedriver_autoinstaller
from selenium import webdriver
#from selenium.webdriver.common.keys import Keys
# import os
#    # to use when 1st time on the machine and then leave comented
# os.system("pip install  selenium ")
# os.system("pip install  chromedriver_autoinstaller ")
chromedriver_autoinstaller.install()
options = webdriver.ChromeOptions()
options.headless = False
driver = webdriver.Chrome(options=options)

解决方案 3:

对于 Ubuntu/Linux:

只需使用它来更新到最新版本:https ://stackoverflow.com/a/57306360/4240654

version=$(curl -s https://chromedriver.storage.googleapis.com/LATEST_RELEASE)
wget -qP "/tmp/" "https://chromedriver.storage.googleapis.com/${version}/chromedriver_linux64.zip"
sudo unzip -o /tmp/chromedriver_linux64.zip -d /usr/bin

如果您需要更新 Chrome,请访问:https: //superuser.com/questions/130260/how-to-update-google-chrome-in-ubuntu

sudo apt-get --only-upgrade install google-chrome-stable

解决方案 4:

您可以使用下面的 shell 脚本来确保下载正确版本的 chrome 驱动程序。您可以在 python 中执行类似操作以使其工作,但您会了解如何继续解决此问题。

%sh
#downloading compatible chrome driver version
#getting the current chrome browser version
**chromeVersion=$(google-chrome --product-version)**
#getting the major version value from the full version
**chromeMajorVersion=${chromeVersion%%.*}**
# setting the base url for getting the release url for the chrome driver
**baseDriverLatestReleaseURL=https://chromedriver.storage.googleapis.com/LATEST_RELEASE_**
#creating the latest release driver url based on the major version of the chrome
**latestDriverReleaseURL=$baseDriverLatestReleaseURL$chromeMajorVersion**
**echo $latestDriverReleaseURL**
#file name of the file that gets downloaded which would contain the full version of the chrome driver to download
**latestDriverVersionFileName="LATEST_RELEASE_"$chromeMajorVersion**
#downloading the file that would contain the full release version compatible with the major release of the chrome browser version
**wget $latestDriverReleaseURL** 
#reading the file to get the version of the chrome driver that we should download
**latestFullDriverVersion=$(cat $latestDriverVersionFileName)**
**echo $latestFullDriverVersion**
#creating the final URL by passing the compatible version of the chrome driver that we should download
**finalURL="https://chromedriver.storage.googleapis.com/"$latestFullDriverVersion"/chromedriver_linux64.zip"**
**echo $finalURL**
**wget $finalURL**

在 databricks 环境上运行计划作业时,我能够使用上述方法获取兼容版本的 chrome 浏览器和 chrome 驱动程序,并且它运行良好,没有任何问题。

希望它能以某种方式帮助其他人。

解决方案 5:

是的,你可以。

问题:“当 Chrome 浏览器通过 Python selenium 自动更新时,如何使用特定版本的 ChromeDriver”

正如您正确指出的那样,Chrome 浏览器会自动更新。如果 ChromeDriver 是您计算机上针对某个特定版本的 Chrome 浏览器的静态文件,则意味着每次浏览器更新时您都必须下载新的 ChromeDriver。

幸运的是,还有一种方法可以自动更新 ChromeDriver!

您可以使用 webdrive-manager 自动使用正确的 chromedriver。

安装 webdrive-manager:

pip install webdriver-manager

然后在 python 中使用该驱动程序,如下所示

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

解决方案 6:

对我来说这解决了这个问题:

pip install --upgrade --force-reinstall chromedriver-binary-auto

解决方案 7:

这是我构建的(还使用了另一个 stackoverflow 线程中的一些预先编写的代码),它可以为你工作。我每次都将脚本设置为从全局驱动程序脚本运行,以确保它使用正确的 ChromeDriver.exe 文件。

但是,您需要先确保在遇到此问题之前安装了新驱动程序,这些脚本将自动下载最新版本/查找最新版本的 ChromeDriver 并将其下载到新的文件夹位置。只有在您的 Chrome 版本更新后,它才会使用新的文件夹位置。如果 chrome 浏览器版本更新并且 chromedriver.storage.googleapis.com 上没有可用版本,则脚本应该会正常失败。

我在操作系统路径中设置了四个脚本,以便可以全局访问我的驱动程序。以下是我用来更新浏览器的脚本。

希望这是有意义的。

干杯!Matt

– 获取文件属性.py –

# as per https://stackoverflow.com/questions/580924/python-windows-file-version-attribute

import win32api

#==============================================================================
def getFileProperties(fname):
#==============================================================================
    """
    Read all properties of the given file return them as a dictionary.
    """
    propNames = ('Comments', 'InternalName', 'ProductName',
        'CompanyName', 'LegalCopyright', 'ProductVersion',
        'FileDescription', 'LegalTrademarks', 'PrivateBuild',
        'FileVersion', 'OriginalFilename', 'SpecialBuild')

    props = {'FixedFileInfo': None, 'StringFileInfo': None, 'FileVersion': None}

    try:
        # backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc
        fixedInfo = win32api.GetFileVersionInfo(fname, '\\')
        props['FixedFileInfo'] = fixedInfo
        props['FileVersion'] = "%d.%d.%d.%d" % (fixedInfo['FileVersionMS'] / 65536,
                fixedInfo['FileVersionMS'] % 65536, fixedInfo['FileVersionLS'] / 65536,
                fixedInfo['FileVersionLS'] % 65536)

        # VarFileInfoTranslation returns list of available (language, codepage)
        # pairs that can be used to retreive string info. We are using only the first pair.
        lang, codepage = win32api.GetFileVersionInfo(fname, '\\VarFileInfo\\Translation')[0]

        # any other must be of the form StringfileInfo%04X%04Xparm_name, middle
        # two are language/codepage pair returned from above

        strInfo = {}
        for propName in propNames:
            strInfoPath = u'\\StringFileInfo\\%04X%04X\\%s' % (lang, codepage, propName)
            ## print str_info
            strInfo[propName] = win32api.GetFileVersionInfo(fname, strInfoPath)

        props['StringFileInfo'] = strInfo
    except:
        pass

    return props

--Chrome版本.py--

from getFileProperties import *

chrome_browser = #'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' -- ENTER YOUR Chrome.exe filepath


cb_dictionary = getFileProperties(chrome_browser) # returns whole string of version (ie. 76.0.111)

chrome_browser_version = cb_dictionary['FileVersion'][:2] # substring version to capabable version (ie. 77 / 76)


nextVersion = str(int(chrome_browser_version) +1) # grabs the next version of the chrome browser

lastVersion = str(int(chrome_browser_version) -1) # grabs the last version of the chrome browser

-- ChromeDriverAutomation.py --

from ChromeVersion import chrome_browser_version, nextVersion, lastVersion


driverName = "\\chromedriver.exe"

# defining base file directory of chrome drivers
driver_loc = #"C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37-32\\ChromeDriver\\\" -- ENTER the file path of your exe
# -- I created a separate folder to house the versions of chromedriver, previous versions will be deleted after downloading the newest version.
# ie. version 75 will be deleted after 77 has been downloaded.

# defining the file path of your exe file automatically updating based on your browsers current version of chrome.
currentPath = driver_loc + chrome_browser_version + driverName 
# check file directories to see if chrome drivers exist in nextVersion


import os.path

# check if new version of drive exists --> only continue if it doesn't
Newpath = driver_loc + nextVersion

# check if we have already downloaded the newest version of the browser, ie if we have version 76, and have already downloaded a version of 77, we don't need to run any more of the script.
newfileloc = Newpath + driverName
exists = os.path.exists(newfileloc)


if (exists == False):

    #open chrome driver and attempt to download new chrome driver exe file.

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.chrome.options import Options
    import time
    chrome_options = Options()
    executable_path = currentPath
    driver = webdriver.Chrome(executable_path=executable_path, options=chrome_options)

    # opening up url of chromedriver to get new version of chromedriver.
    chromeDriverURL = 'https://chromedriver.storage.googleapis.com/index.html?path=' + nextVersion 

    driver.get(chromeDriverURL)

    time.sleep(5)
    # find records of table rows
    table = driver.find_elements_by_css_selector('tr')


    # check the length of the table
    Table_len = len(table)

    # ensure that table length is greater than 4, else fail. -- table length of 4 is default when there are no availble updates
    if (Table_len > 4 ):

        # define string value of link
        rowText = table[(len(table)-2)].text[:6]
        time.sleep(1)
        # select the value of the row
        driver.find_element_by_xpath('//*[contains(text(),' + '"' + str(rowText) + '"'+')]').click()
        time.sleep(1)
        #select chromedriver zip for windows 
        driver.find_element_by_xpath('//*[contains(text(),' + '"' + "win32" + '"'+')]').click()

        time.sleep(3)
        driver.quit()

        from zipfile import ZipFile
        import shutil


        fileName = #r"C:UsersAdministratorDownloadschromedriver_win32.zip" --> enter your download path here.




        # Create a ZipFile Object and load sample.zip in it
        with ZipFile(fileName, 'r') as zipObj:
           # Extract all the contents of zip file in different directory
           zipObj.extractall(Newpath)


        # delete downloaded file
        os.remove(fileName)



        # defining old chrome driver location
        oldPath = driver_loc + lastVersion
        oldpathexists = os.path.exists(oldPath)

        # this deletes the old folder with the older version of chromedriver in it (version 75, once 77 has been downloaded)
        if(oldpathexists == True):
            shutil.rmtree(oldPath, ignore_errors=True)



exit()

https://github.com/MattWaller/ChromeDriverAutoUpdate

解决方案 8:

也许这会对你有所帮助。我设法使用 ChromeDriver 版本 96.0.4664.45 在 JUPYTER 中编辑,我之前使用过 Pycharm,但它没有响应。

解决方案 9:

这是我的解决方案。我会从https://googlechromelabs.github.io/chrome-for-testing/下载特定的 Chrome(或任何我想使用的浏览器),并将其放在测试可访问的目录中。创建 webdriver 实例时,我会将 ChromeDriver 的“BinaryLocation”属性设置为浏览器的路径。这是我的示例 C#

string path = "drivers"; // webdrivers are in a subdirectory
var options = new ChromeOptions
{
    BinaryLocation = @"SOMEPATHchrome-win64chrome.exe",
};
driver = new ChromeDriver(path, options);

这样我就可以使用与 webdrivers 和浏览器完全相同的版本。我确信同样的方法也适用于其他语言。

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1579  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1355  
  信创产品在政府采购中的占比分析随着信息技术的飞速发展以及国家对信息安全重视程度的不断提高,信创产业应运而生并迅速崛起。信创,即信息技术应用创新,旨在实现信息技术领域的自主可控,减少对国外技术的依赖,保障国家信息安全。政府采购作为推动信创产业发展的重要力量,其对信创产品的采购占比情况备受关注。这不仅关系到信创产业的发展前...
信创和国产化的区别   8  
  信创,即信息技术应用创新产业,旨在实现信息技术领域的自主可控,摆脱对国外技术的依赖。近年来,国货国用信创发展势头迅猛,在诸多领域取得了显著成果。这一发展趋势对科技创新产生了深远的推动作用,不仅提升了我国在信息技术领域的自主创新能力,还为经济社会的数字化转型提供了坚实支撑。信创推动核心技术突破信创产业的发展促使企业和科研...
信创工作   9  
  信创技术,即信息技术应用创新产业,旨在实现信息技术领域的自主可控与安全可靠。近年来,信创技术发展迅猛,对中小企业产生了深远的影响,带来了诸多不可忽视的价值。在数字化转型的浪潮中,中小企业面临着激烈的市场竞争和复杂多变的环境,信创技术的出现为它们提供了新的发展机遇和支撑。信创技术对中小企业的影响技术架构变革信创技术促使中...
信创国产化   8  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用