DEV Community

yubaraj singh
yubaraj singh

Posted on

Updating WebDriver matching with browser automatically using python

I had built a web application that need web automation. So I used python Selenium for web automation. The application software was running smoothly and it has only one problem that occurs when my browser(chrome) update automatically and the software stops working. So to keep running, I frequently download the matching version of webdriver and replace the old webdriver. So to automatically download the new webdriver of chrome here are the steps to follow:
import required package

from selenium import webdriver
import requests
import wget
import zipfile
import os

Enter fullscreen mode Exit fullscreen mode

get Chrome browser version and chrome webdriver version

driver = webdriver.Chrome()
browser_version = driver.capabilities['browserVersion']
driver_version = driver.capabilities['chrome']['chromedriverVersion'].split(' ')[0]
print("browser version",browser_version)
print("driver version",driver_version)
Enter fullscreen mode Exit fullscreen mode

Then we need to check if the chrome version is matching or not and apply if-else condition

if browser_version[0:2] != driver_version[0:2]: 

    driver.close()
    driver.quit()

    os.remove(r'chromedriver.exe')

    # get the latest chrome driver version number
    url = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE'
    response = requests.get(url)
    version_number = response.text

    # build the donwload url
    download_url = "https://chromedriver.storage.googleapis.com/" + version_number +"/chromedriver_win32.zip"

    # download the zip file using the url built above
    latest_driver_zip = wget.download(download_url,'chromedriver.zip')
    # extract the zip file
    with zipfile.ZipFile(latest_driver_zip, 'r') as zip_ref:
        zip_ref.extractall() # you can specify the destination folder path here
    # delete the zip file downloaded above
    os.remove(latest_driver_zip)

else:
    print("rock and roll your are good to go")
Enter fullscreen mode Exit fullscreen mode

so hereafter I checked the version and using if condition the version isn't matching then I close the running webdriver and quit the webdriver.
Afterwards, using request.get to get the latest version of chrome webdriver.

  • Then using wget , I download the zip file.
  • lastly, unpack the zip file using zip_ref and remove the zip file.  Now we are good to go with if the version isn't matching condition. If the version are matching then our web automation will run smoothly without any trouble and there is no need to update the webdriver manually.

So in this way I was able to automatically download the matching version of chrome webdriver.

Reference:
Automatic download of appropriate chromedriver for Selenium in Python - Stack Overflow

Top comments (0)