selenium-webdriver Locating Web Elements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • ByChained(params By[] bys)

Remarks

Items are found in Selenium through the use of locators and the By class. In order to make a robust automation project with Selenium, one should use locators for Web Elements smartly. The locators should be descriptive, unique, and unlikely to change so you won't get false positives in tests for example. The priority is to use:

  1. ID - since it's unique and you'll get exactly the element you want.
  2. Class Name - It's descriptive and can be unique in a given context.
  3. CSS (better performance than xpath) - For more complicated selectors.
  4. XPATH - Where CSS can't be used (XPATH Axis), e.g. div::parent.

The rest of the locators are prone to changes or rendering, and preferebly be avoided.

Rule of thumb: if your code cannot locate a particular element, one reason could be that your code hasn't waited for all the DOM elements to download. Consider telling your program to "wait" for a short period of time (try 3-5 seconds, and then slowly increase as needed) before searching for said element. Here is an example in Python, taken from this question:

from selenium import webdriver
import time

browser = webdriver.Firefox()
browser.get("https://app.website.com")

reports_element = browser.find_element_by_xpath("//button[contains(text(), 'Reports')]")

# Element not found! Try giving time for the browser to download all DOM elements:
time.sleep(10)

reports_element = browser.find_element_by_xpath("//button[contains(text(), 'Reports')]")
# This returns correct value!



Got any selenium-webdriver Question?