Это то, что я построил (также использовал некоторый предзаписанный код из другого потока stackoverflow), оно может работать для вас.Я каждый раз настраиваю свои скрипты для запуска из глобального скрипта драйвера, чтобы убедиться, что он использует правильный файл ChromeDriver.exe.
Но перед тем, как столкнуться с этой проблемой, необходимо сначала убедиться, что вы устанавливаете новый драйвер, эти сценарии автоматически загрузят самую новую версию / найдут самую новую версию ChromeDriver и загрузят ее в новую папку с файлами.место нахождения.Он будет использовать новое расположение папок только после обновления вашей версии Chrome.Сценарий должен завершиться неудачно, если браузер обновляет версию chrome, а на chromedriver.storage.googleapis.com нет доступной версии.
Я установил четыре сценария в моем пути os, чтобы я мог получить доступ к своему драйверу глобально.Ниже приведены сценарии, которые я использую для обновления своего браузера.
Надеюсь, это имеет смысл.
Ура!Matt
- getFileProperties.py -
# as per /563698/atribut-versiya-faila-windows-python
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)
# \VarFileInfo\Translation 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%04X\parm_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
- ChromeVersion.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:\Users\Administrator\Downloads\chromedriver_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