Selenium with Python

Posted January 29, 2019 by Rokas Balsys



Introduction tutorial part #2

Welcome to second SELENIUM with Python tutorial part, where I will show you how use use SELENIUM to start automating commonly used and custom browsers, how to open and close new browsing tabs.

In previous tutorial we wrote a simple python script to open Firefox browser and use gooogle search with few lines of code.

In this tutorial we'll write 3 new functions: to start browser, to open new tab and to close current tab. So lets begin.

We will begin with starting browser function. So we call this function with argument "browser=1" when we'll use our default browser and "browser=2" when we want to use our custom browser. I tried this code with Google ChromiumGoogle Chromium, but you can try whatever you want, just write correct path to browser location and browser driver. I commented few lines of code, if you want you can remove comment sign from them, but I wont use them in my code. And at the last line we return "driver" because we'll use this in all our future functions to control a browser. We call StartBrowser() function from main code, when we want to start browsing session.

def StartBrowser(browser=1, browser_location='', driver_path=''):
    if browser == 1:
        driver = webdriver.Firefox()
    if browser == 2:
        options = webdriver.ChromeOptions()
        options.binary_location = browser_location
        driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options)
    #driver.implicitly_wait(30)
    #driver.set_window_size(1920,1080)
    #driver.maximize_window()
    return driver

Mostly when we are browsing something on internet we would like to use new tabs, so we'll write a function to open it. Selenium webdriver don't have integrated command to open new tabs on internet, so we'll write our own by using script. Before opening new tab we are checking how many tabs we have currently opened: "len(driver.window_handles)". Then we execute our script to open a new tab, and we are waiting for it, by every 500ms checking our tabs count, when our tabs count increase by one it means that new tab opened and we may switch to it:

def OpenNewTab(driver, Link):
    window_count = len(driver.window_handles)
    driver.execute_script('''window.open("'''+Link+'''","_blank");''')
    while len(driver.window_handles) != window_count+1:
        time.sleep(0.5)
    driver.switch_to.window(driver.window_handles[-1])

And lastly, we would usually we would like to know how to close these tabs. It's quite easy, we will write a new function for that, with simple command: "driver.close()". In this function we'll handle our first exception, which occurs when we are trying close not existing window. For example when we close one window and we trying to close it again, we get this exception:

def DriverClose(driver):
    try:
        driver.close()
    except NoSuchWindowException:
        print("NoSuchWindowException in driver.close()")
        return False
    return True

Final tutorial code:

from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchWindowException

def DriverClose(driver):
    try:
        driver.close()
    except NoSuchWindowException:
        print("NoSuchWindowException in driver.close()")
        return False
    return True

def StartBrowser(browser=1, browser_location='', driver_path=''):
    if browser == 1:
        driver = webdriver.Firefox()
    if browser == 2:
        options = webdriver.ChromeOptions()
        options.binary_location = browser_location
        driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options)
    #driver.implicitly_wait(30)
    #driver.set_window_size(1920,1080)
    #driver.maximize_window()
    return driver

def OpenNewTab(driver, Link):
    window_count = len(driver.window_handles)
    driver.execute_script('''window.open("'''+Link+'''","_blank");''')
    while len(driver.window_handles) != window_count+1:
        time.sleep(0.5)
    driver.switch_to.window(driver.window_handles[-1])

browser_location = "C:/Users/HOME/Desktop/chrome-win/chrome.exe"
driver_path = "C:/Users/HOME/Desktop/chrome-win/chromedriver.exe"
driver = StartBrowser(2, browser_location, driver_path)
time.sleep(1)
driver.get("https://www.google.com")
time.sleep(1)
OpenNewTab(driver, "https://www.google.com")

In above code we are starting a new browser session with "driver = StartBrowser(2, browser_location, driver_path)" line, if you would use it with Firefox browser, change it to "driver = StartBrowser(1)". Then we open google search page and in one second we open same page in a new tab. If you would like to see how we close these tabs, check my YouTube video tutorial.


Thats all for this short tutorial, in next part we'll cover how to handle exceptions and what are methods to find HTML object on page.