The Ultimate Selenium Cheat Sheet with Python for Test Automation


Opening a link or document

It is important to open the target URL (or test URL) before performing any operations on the web elements present on the page. Next, you will see several ways to open a URL in Selenium with Python:

driver.get (URL)

Method driver.get() goes to the page that is passed to the method as a parameter. Selenium WebDriver will wait until the page is fully loaded, after which it will fire the event “onload“And returns control to the test script. The article Selenium Waits in Python you can find more information on waiting handling in Selenium.

 driver.get("https://www.lambdatest.com")

Refreshing the page

There are scenarios in which you need to update the page content. The page refresh method in Selenium WebDriver is used to refresh web pages.

Method driver.refresh() refreshes the current web page. It takes no arguments and returns no values.

driver.refresh()

Entering text into a web element

Method send_keys() in Python it is used to enter text into a text element. This text is passed to the method as an argument. The same technique can be used to simulate key presses in any field (for example, in form input fields).

Usage example send_keys()where the email is passed to the text element on the LambdaTest registration page:

from selenium import webdriver
  
# create webdriver object
driver = webdriver.Chrome()
  
# get lambdatest
driver.get("https://www.lambdatest.com/")
  
# get element 
element = driver.find_element_by_id("useremail")
  
# send keys 
element.send_keys("emailid@lambdatest.com")

Remove text in a web item

Method element.clear() in Selenium it is used to remove text from fields like form input fields etc.

An example of using the method to clear the contents of an email input field on the LambdaTest home page:

from selenium import webdriver
  
# create webdriver object
driver = webdriver.Chrome()
  
# get lambdatest
driver.get("https://www.lambdatest.com/")
  
# get element 
element = driver.find_element_by_id("useremail")
  
# send keys 
element.clear()

Clicking on a web element

Method element.click() in Selenium it is used to click on an element such as anchor link, button, etc.

Like this using the method click() you can click on the button on the LambdaTest home page:

from selenium import webdriver
  
# create webdriver object
driver = webdriver.Chrome()
  
# get lambdatest
driver.get("https://www.lambdatest.com/")
  
# get element 
element = driver.find_element_by_id("useremail")
  
# send keys 
element.send_keys("emailid@lambdatest.com")
  
# get element 
button_element = driver.find_element_by_link_text("Start Free Testing")
  
# click the element
button_element.click()

Dragging and dropping a web element

Drag and drop is one of the widely used scripts in popular applications (or programs) like Canvas, Google Drive, Trello, Asana, etc. Method drag_and_drop(element, target) in Selenium helps automate the functionality of dragging and dropping web elements from the source and bringing them to the target area (or element).

At the class Actions Selenium has two methods with which you can perform drag and drop operations when testing cross browser compatibility. Be sure to check out our detailed guide, which has information on how drag and drop in Selenium.

Here is a simple example of using the method drag_and_drop():

element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")

from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()

Option selection

Select(element) provides useful methods for interacting with dropdowns, selecting items, and more.

This is how you can select an element by index:

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('city'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)

Here are some variations on how to select the desired item using the method select_by_*():

Method

Description

select_by_index(индекс)

The method takes an integer value – the index of the option we want to select.

select_by_visible_text(“text”)

The method takes a string value and selects an option that contains the desired text.

select_by_value(meaning)

The method takes a string value and selects a parameter with the same attribute value.

deselect_all()

The method allows you to deselect all selected options.

Navigation between windows

If you have multiple windows, you may need to switch between them before performing actions on web elements from the DOM.

driver.switch_to_window (“window_name”)

Method switch_to_window() Selenium WebDriver allows you to switch to the desired window. The window handle is passed as an argument to the method switch_to_window()

driver.switch_to_window("window_handle")

All subsequent calls to WebDriver are now applied to the focused window (or to a new window after switching).

driver.window_handles

Property window_handles WebDriver returns handles to windows. Now you can use the method switch_to_window() to go to any window from the list window_handles

for handle in driver.window_handles:
    driver.switch_to_window(handle)

driver.current_window_handle

Method current_window_handle() returns a handle to the current window (or window with focus).

handler = driver.current_window_handle 

Switch to iFrame

Selenium WebDriver is unable to access or find web elements inside an iFrame in the context of the home page. Hence, you need to switch to the iFrame before accessing the elements within it.

driver.switch_to_frame (“iframe_name”)

Method switch_to_frame() in Selenium Python allows changing the WebDriver context from the main page context. We can also access subframes by adding a dot between the path and the index.

driver.switch_to_frame("frame_name.0.child")

driver.switch_to_default_content ()

The method allows you to navigate back to the context of the master page.

driver.switch_to_default_content()

Handling pop-ups and alerts

There are only three main types of pop-ups and alerts that are commonly used in web applications:

  • Simple Alert

  • Confirmation Alert

  • Prompt Alert

You can switch to the alert, reject it, or accept it. Check out our detailed guidance on handling alerts and pop-ups in Selenium. Even though it uses C #, the basics remain the same!

driver.switch_to.alert

Property switch_to.alert in WebDriver returns the currently open object alert… You can accept it, reject it, read the content, or enter it on the command line.

alert_obj = driver.switch_to.alert

alert_obj.accept ()

Once you have a window handle alert (For example, alert_obj), method accept() will help you accept the warning popup.

alert_obj = driver.switch_to.alert 
alert_obj.accept()

alert_obj.dismiss ()

After you switched to the window alert (For example, alert_obj), you can use the method dismiss()to dismiss the warning popup.

alert_obj = driver.switch_to.alert 
alert_obj.accept()

alert_obj.text ()

This method is used to retrieve the message from the alert popup.

alert_obj = driver.switch_to.alert 
msg = alert_obj.text()
print(msg)

Getting the page code

Method page_source() in Selenium WebDriver is used to get the page code.

page_source = driver.page_source

Browsing history navigation

Selenium WebDriver in Python provides several functions for moving back and forth through browser history.

driver.forward ()

This method allows scripts to move one step forward in browser history.

driver.forward()

driver.back ()

This method allows scripts to navigate one step back in browser history.

driver.back()

Selenium Cookie Handling

Cookie handling in Selenium WebDriver is one of the common scenarios that you might have to deal with when automating. Various operations can be performed such as add, delete, get the cookie name, and more.

driver.add_cookie ()

This method helps to set up a cookie for a Selenium session. It accepts values ​​as a key-value pair.

# Go to the domain
driver.get("https://www.lambdatest.com/")

# Now set the cookie. 
cookie = {'name' : 'user', 'value' : 'vinayak'}
driver.add_cookie(cookie)

driver.get_cookies ()

This method will dump all available cookies for the current Selenium session.

# Go to the domain
driver.get("https://www.lambdatest.com/")

driver.get_cookies()

driver.delete_cookie ()

It is possible to delete a specific cookie or all cookies associated with the current Selenium session.

# delete one cookie
driver.delete_cookie(cookie)
# delete all cookies
driver.delete_all_cookies()

Setting the window size

# Setting the window size to 1200 * 800
driver.set_window_size(1200, 800)

Setting timeouts in Selenium WebDriver

When a browser loads a page, the web elements inside it may load at different intervals. This can make it difficult to interact with dynamic elements present on the page.

If the element is not present in the DOM of the web page, the method locate will throw an exception. Expectations in Selenium allow you to add delays (in milliseconds or seconds) between actions performed between page loading and finding the desired web element.

Implicit wait and explicit wait are two main ways to add delays to Selenium code in Python to handle dynamic web elements on a page.

Implicit waiting in Selenium Python

An implicit wait informs Selenium WebDriver to check the DOM for a specified period of time when trying to find a web element that is not available immediately after the page is loaded.

By default, implicit wait is zero. However, once we define it, it is set for the lifetime of the WebDriver object. Check out the detailed tutorial that demonstrates the use of implicit wait in Selenium Python.

from selenium import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(10) # in seconds
driver.get("https://www.lambdatest.com/")
element = driver.find_element_by_id("testing_form")

Explicit wait in Selenium Python

Explicit expectation in Selenium with Python it is used when we want to wait for a certain condition to be met before proceeding.

Selenium WebDriver has several convenient methods that allow you to wait until a certain condition is met. For example, an explicit expectation can be obtained using the class webdriverWait in combination with expected conditions in Selenium.

Here are some of the expected conditions that can be used in conjunction with an explicit expectation in Selenium Python:

  • presence_of_all_elements_located

  • text_to_be_present_in_element

  • text_to_be_present_in_element_value

  • frame_to_be_available_and_switch_to_it

  • invisibility_of_element_located

  • title_is

  • title_contains

  • presence_of_element_located

  • visibility_of_element_located

  • visibility_of

  • element_located_selection_state_to_be

  • alert_is_present

  • element_to_be_clickable

  • staleness_of

  • element_to_be_selected

  • element_located_to_be_selected

  • Element_selection_state_to_be

There is an example below that demonstrates the use of an explicit wait, which performs a non-blocking wait of 10 seconds until the required web element is found (using its ID attribute):

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.lambdatest.com/")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "testing_form"))
    )
except:
    print(“some error happen !!”)

Taking screenshots

During the automation process, you may need to take a screenshot of an entire page or a specific web element.

This way you can check what went wrong while running the test. Take screenshots of web elements using seleniumif you want to check which specific element caused an error while executing a test.

Method save_screenshot() Selenium WebDriver is used to create screenshots of the web page.

capture_path="C:/capture/your_desired_filename.png"
driver.save_screenshot(capture_path)

This certification is designed for professionals who want to develop advanced practical skills in test automation with Selenium in Python and take their careers to the next level.

LambdaTest Selenium Python 101 Certification Brief:

Conclusion

Python is one of the most popular languages ​​and there is no doubt that you can perform complex operations with Selenium with just a few lines of code. In this Selenium in Python Cheat Sheet, we looked at some of the widely used Selenium commands that are primarily used for testing. cross-browser compatibility

This Selenium Cheat Sheet can be used as a guide (or reference) for a quick introduction to commands that might be of interest to your case. I hope you find it useful and be sure to let me know if you come across any Selenium team that should be part of it.

Happy Python Automated Testing!


Material prepared as part of the course Python QA Engineer.

We invite everyone to a free two-day intensive “About Python for the Automator: The Basics of the Basics.” Content:
1. A few words about Python.
2. Let’s figure out what data types / objects are in Python and why know about it at all.
3. Decorators and their use in autotests: let’s practice writing decorators and look for useful uses for them.

Suitable for those who not so long ago automate in Python, but did not understand the possibilities and limitations of Python, and for those who are still new, but would like to. For those who have been programming in Python for a long time, it will be boring and you are unlikely to learn something new.

Method set_window_size() is used to adjust the desired dimensions of the browser window (width and height).