selenium-webdriver Basic Selenium Webdriver Program Python


Example

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def set_up_driver():
    path_to_chrome_driver = 'chromedriver'
    return webdriver.Chrome(executable_path=path_to_chrome_driver)

def get_google():
    driver = set_up_driver()
    driver.get('http://www.google.com')
    tear_down(driver)

def tear_down(driver):
    driver.quit()

if '__main__' == __name__:
    get_google()

The above 'program' will navigate to the Google homepage, and then close down the browser before completing.

if '__main__' == __name__:
    get_google()

First we have our main function, our point of entry into the program, that calls get_google().

def get_google():
    driver = set_up_driver()

get_google() then starts by creating our driver instance via set_up_driver():

def set_up_driver():
    path_to_chrome_driver = 'chromedriver'
    return webdriver.Chrome(executable_path=path_to_chrome_driver)

Whereby we state where chromedriver.exe is located, and instantiate our driver object with this path. The remainder of get_google() navigates to Google:

driver.get('http://www.google.com')

And then calls tear_down() passing the driver object:

tear_down(driver)

tear_down() simply contains one line to shut down our driver object:

driver.quit()

This tells the driver to close all open browser windows and dispose of the browser object, as we have no other code after this call this effectively ends the program.