Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to automatically update chromedriver in my Test Automation Suite directory?

I have an Automation framework using Selenium and Python. For running Chrome browser I have placed chrome driver in one of the folders in my automation framework. Now the problem is chrome driver gets udpated after certain period of time and my script starts failing because of that and I need to place the updated chrome driver in the directory every time when it gets updated by Google.

Is there any automated way I can implement to resolve this issue?

like image 716
Python_Novice Avatar asked Nov 07 '22 06:11

Python_Novice


1 Answers

I had the same problem, so I made a selenium script to automatically download the exe file from chromedrivers site and get all my scripts to reference the current location of the chromedriver.exe file in my python directory. I run this script parallel to google updates in the scheduler, so that when chrome gets updated so does the driver.

Feel free to use it / retool it.

-- getFileProperties.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)

        # \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

like image 83
Waller511 Avatar answered Nov 15 '22 12:11

Waller511