Selenium Cheat Sheet in Python

Ivan
Ivan
Oct 23, 2019 · 4 min read

For Java version the link is here

Install Python

To install Python 3.x go to this link

IDE

You can use any text editor. I recommend PyCharm Community as it is free and have extensive support. For list of popular editors , this are the links

Install Selenium

To install Selenium webdriver ,

pip3 install selenium

Dirty our hands !

Import Selenium

from selenium import webdriver

Browsers support (Firefox , Chrome , Internet Explorer, Edge , Opera)

Driver setup:

Chrome:

chromedriver = webdriver.Chrome(“Chrome Driver Path”)

To download: Visit Here

Firefox:

firefoxdriver = webdriver.Firefox(“Firefox Driver Path”)

To download: Visit GitHub

Internet Explorer:

iedriver = webdriver.IE(“­IE Driver Path”)

To download: Visit Here

Edge:

edgedriver = webdriver.Edge(“Edge Driver Path”)

To download: Visit Here

Opera:

operadriver = webdriver.Opera(“Opera Driver Path”)

To download: visit GitHub

Browser Arguments:

–headless

To open browser in headless mode. Works in both Chrome and Firefox browser

–start-maximized

To start browser maximized to screen. Requires only for Chrome browser. Firefox by default starts maximized

–incognito

To open private chrome browser

–disable-notifications

To disable notifications, works Only in Chrome browser

Example:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--start-maximized")
options.add_argument("--disable-notifications")
options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=options, executable_path="Path to driver")

Alternative

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()options.add_argument("--incognito","--start-maximized","--headless")
driver = webdriver.Chrome(chrome_options=options, executable_path="Path to driver")

Launch URL

driver.get(url)

Retrieve Browser Details:

driver.title
driver.window_handles
driver.current_window_handles
driver.current_url
driver.page_source

Navigation

driver.get(url)
driver.back()
driver.forward()
driver.refresh()

Locating Elements

By id

<input id=”login” type=”text” />

element = driver.find_element_by_id(“login”)

By Class Name

<input class=”gLFyf” type=”text” />

element = driver.find_element_by_class_name(“gLFyf”)

By Name

<input name=”z” type=”text” />

element = driver.find_element_by_name(“z”)

By Tag Name

<div id=”login” >…</div>

element = driver.find_element_by_tag_name(“div”)

By Link Text

<a href=”#”>News</a>

element = driver.find_element_by_link_text(“News”)

By XPath

<form id=”login” action=”submit” method=”get”>

Username: <input type=”text” />

Password: <input type=”password” />

</form>

element = driver.find_element_by_xpath(“//form[@id='login']/input”)

By CSS Selector

<form id=”login” action=”submit” method=”get”>

Username: <input type=”text” />

Password: <input type=”password” />

</form>

element = driver.find_element_by_css_selector(“input.username”)

Clicking / Input text

Clicking button

chromedriver.find_element_by_class_name("gLFyf").click()

Send Text

chromedriver.find_element_by_class_name("gLFyf").send_keys("hello")

Waits

Implicit Waits

An implicit wait instructs Selenium WebDriver to poll DOM for a certain amount of time, this time can be specified, when trying to find an element or elements that are not available immediately.

from selenium import webdriverdriver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("https://www.google.com")
driver.find_element_by_name("q").click()

Explicit Waits

Explicit wait make the webdriver wait until certain conditions are fulfilled . Example of a wait

try:    element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.NAME, "q")))
# Type "selenium"
element.send_keys("selenium")
# Type Enter
element.send_keys(Keys.ENTER)
except TimeoutException:
print("Failed to load search bar at www.google.com")

List of explicit waits

  • title_is
  • title_contains
  • presence_of_element_located
  • visibility_of_element_located
  • visibility_of
  • 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
  • element_to_be_clickable
  • staleness_of
  • element_to_be_selected
  • element_located_to_be_selected
  • element_selection_state_to_be
  • element_located_selection_state_to_be
  • alert_is_present

Loading a list of elements like li and selecting one of the element

searchButton_css = "button.btn.Searchbox__searchButton.Searchbox__searchButton--active[data-selenium='searchButton']"
inputDestination_css = "input[data-selenium='textInput']"
suggestedDestinationList_css = "ul.AutocompleteList"
stringBali = "Bali"
# Create a new chromedriver instance
driver = webdriver.Chrome()
# Go to www.agoda.com
driver.get("https://www.agoda.com")
try:
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, searchButton_css)))
driver.find_element_by_css_selector(inputDestination_css).send_keys("Bali Indonesia")
except TimeoutException:
print("Failed to load page")
try:
elements = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, suggestedDestinationList_css)))
items = driver.find_element_by_css_selector(suggestedDestinationList_css)
elementsList = items.find_elements_by_tag_name("li")
for item in elementsList:
print (item.text +"\n")
if item.text in stringBali:
item.click()
break
except TimeoutException: print("Failed to load list")

Read Attribute

print("Title of searchbar : "+ chromedriver.find_element_by_name("q").get_attribute("jsaction"))

Get CSS

# import the webdriver
from selenium import webdriver
# set exe path and open the browser.
driver = webdriver.Chrome()
# open website
driver.get("https://google.com")
# get the css value
cssValue = driver.find_element_by_name("q").value_of_css_property("font-size")
print("font size searchbar : "+ cssValue)

CSS values varies on different browser, you may not get same values for all the browser.

Capture Screenshot

# import the webdriver
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(url)
driver.get_screenshot_as_file('sample_screenshot_2.png')driver.save_screenshot('screenshot1.png')

save_screenshot(“filename”) and get_screenshot_as_file(“filename) will work only when the extension of file is “png”. Otherwise the content cannot be viewed.

is_selected()

is_selected() method in selenium verifies if an element (such as checkbox) is selected or not. is_selected() method returns a boolean.

# import the webdriver
from selenium import webdriver
driver = webdriver.Chrome();# open website
driver.get("https://google.com/")
# get css value
isSelected = driver.find_element_by_xpath("//input[@id='selected']").is_selected()
print("Is checkbox selected : ", isSelected)
Output : Is checkbox selected : ", False

is_displayed()

is_displayed() method in selenium webdriver verifies and returns a boolean based on the state of the element (such as button) whether it is displayed or not.

# import the webdriver
from selenium import webdriver
driver = webdriver.Chrome()# open website
driver.get("https://google.com")
# get css value
isDisplayed = driver.find_element_by_name("q").is_displayed()
print("Is Searchbar Displayed : ", isDisplayed)

is_enabled()

is_enabled() method in selenium python verifies and returns a boolean based on the state of the element (such as button) whether it is enabled or not.

# import the webdriver
from selenium import webdriver
driver = webdriver.Chrome()# open website
driver.get("https://google.com")
# element enabled
isEnabled = driver.find_element_by_name("q").is_enabled()
print("Is searchbar enabled : ", isEnabled)

Minimum modules to import

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

Original story is published in here

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade