Finding Elements - aclaudio123/selenium-tutorial GitHub Wiki

Finding an Element

There are various strategies to locate elements in a page.

  • find_element_by_id()
  • find_element_by_name()
  • find_element_by_xpath()
  • find_element_by_css_selector()
  • find_element_by_link_text()
  • find_element_by_partial_link_text()
  • find_element_by_class_name()
  • find_element_by_tag_name()

Apart from the methods given above, there is another method used for finding an element. The syntax is as follows:

find_element(by, value).

To use this method, you most import the selenium By class

from selenium.webdriver.common.by import By

Example:

driver.find_element(By.XPATH, "xpath expression")
driver.find_element(By.TAG_NAME, "tag name")

These are the attributes available for By:

  • ID = "id"
  • NAME = "name"
  • XPATH = "xpath expression"
  • CSS_SELECTOR = "css selector expression"
  • LINK_TEXT = "link text"
  • PARTIAL_LINK_TEXT = "partial link text"
  • CLASS_NAME = "class name"
  • TAG_NAME = "tag name"

Finding Multiple Elements

To find multiple elements we use the plural form

  • find_elements_by_name()
  • find_elements_by_xpath()
  • find_elements_by_link_text()
  • find_elements_by_partial_link_text()
  • find_elements_by_tag_name()
  • find_elements_by_class_name()
  • find_elements_by_css_selector()

Similarly, you can use

find_elements(by, value).
from selenium.webdriver.common.by import By

driver.find_elements(By.XPATH, "xpath expression")

The attributes are the same as well:

  • ID = "id"
  • NAME = "name"
  • XPATH = "xpath expression"
  • CSS_SELECTOR = "css selector expression"
  • LINK_TEXT = "link text"
  • PARTIAL_LINK_TEXT = "partial link text"
  • CLASS_NAME = "class name"
  • TAG_NAME = "tag name"
⚠️ **GitHub.com Fallback** ⚠️