Initialize Webdriver


from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\Temp\drivers\chromedriver.exe")
# Open a Web Page
driver.get("https://sqa.stackexchange.com/")

# Go to a Page Previous Page
driver.back()

# Go to the next Page
driver.forward()

Finding an Element in WebPage

# Find an element when the id is known
element = driver.find_element_by_id("")

# Find an element when the Class Name is known
elementtwo = driver.find_element_by_class_name()

# Find an element when the link text us known
elementthree = driver.find_element_by_link_text()

# Find an element when the XPATH is known
sourceelement = driver.find_element_by_xpath("")

# Find an element when using the BY clause
from selenium.webdriver.common.by import By
targetelement = driver.find_element(By.Id, "")

Check for Element States

element.is_displayed()
element.is_enabled()
element.is_selected()

Enter Values into Text Boxes

element.send_keys("test to enter")

from selenium.webdriver.support.ui import Select
dropDown = Select(element)
dropDown.select_by_index(1)
dropDown.select_by_value()
dropDown.select_by_visible_text()

# Select all elements in Drop Down for further handling
dropDown.options()

Handling Alerts

driver.switch_to_alert().accept()
driver.switch_to_alert().dismiss()

Handling Frames

driver.switch_to_frame("name")
# Switch to the parent frame
driver.switch_to_default_content()

Handling Multiple Windows

driver.current_window_handle()
driver.window_handles()
driver.switch_to_window("window name")

Wait Commands

# Definite Sleep / Hard Sleep
import time
time.sleep(10)

# Explicit Wait
from selenium.webdriver.support.wait import WebDriverWait
wait = WebDriverWait(driver, 10)

from selenium.webdriver.support import expected_conditions
wait.until(expected_conditions.element_to_be_clickable(By.XPATH, ""))

Window Scroll

# Scroll down the page by 1000 pixel
driver.execute_script("window.scrollBy(0,1000)","")

# Scroll down the page until the element is visible

driver.execute_script("arguments[0].scrollIntoView();",element)

# Scroll down till the end of Page
driver.execute_script("window.scrollBy(0,document.body.scrollHeight)")

Mouse Actions

from selenium.webdriver import ActionChains
actions = ActionChains(driver)

# Mouse Hover the element
actions.move_to_element(element).perform()

# Double Click the Element
actions.double_click(element).perform()

# Right Click on an Element
actions.context_click(element).perform()

# Drag and Drop Element
actions.drag_and_drop(sourceelement, targetelement).perform()

Taking Screenshots

# save screen shot as it displays in the screen
driver.save_screenshot("filename.png")

# save screenshot for the entire page
driver.get_screenshot_as_file("filename.png")

Terminating Driver Sessions

# close the current browser
driver.close()

# close all the browsers opened by the driver session
driver.quit()

Photo by Hitesh Choudhary on Unsplash

Advertisement