Selenium Element Locating

In Selenium, element locating is the core of automated testing and web page operations.

By locating elements, you can perform operations such as clicking, entering text, and getting attributes on them.

Basic Concepts of Element Locating

What is element locating?

Element locating refers to finding specific elements in a web page by some means (such as buttons, input boxes, links, etc.).

Why is element locating needed?

Automated operations require precisely finding the target element before performing subsequent operations (such as clicking, entering, etc.).

Uniqueness of located elements.

Ensure that the located element is unique to avoid operating on the wrong element.


Locating Methods

Selenium provides multiple element locating methods, commonly including the following:

1. Locate by ID

Method:find_element(By.ID, "id_value")

Description:Locate by the element's id attribute.

from selenium.webdriver.common.by import By

element = driver.find_element(By.ID, "username")

2. Locate by Name

Method:find_element(By.NAME, "name_value")

Description:Locate by the element's name attribute.

element = driver.find_element(By.NAME, "password")

3. Locate by Class Name

Method:find_element(By.CLASS_NAME, "class_name")

Description:Locate by the element's class attribute.

element = driver.find_element(By.CLASS_NAME, "submit-btn")

4. Locate by Tag Name

Method:find_element(By.TAG_NAME, "tag_name")

Description:Locate by the element's tag name (such as <div>, <input>, etc.).

 element = driver.find_element(By.TAG_NAME, "input")

5. Locate by CSS Selector

Method:find_element(By.CSS_SELECTOR, "css_selector")

Description:Locate elements by CSS selectors.

 element = driver.find_element(By.CSS_SELECTOR, "input#username")

6. Locate by XPath

Method:find_element(By.XPATH, "xpath_expression")

Description:Locate elements by XPath expressions.

 element = driver.find_element(By.XPATH, "//input[@id='username']")

7. Locate by Link Text

Method:find_element(By.LINK_TEXT, "link_text")

Description:Locate by the link's text content (applicable to <a> tags).

 element = driver.find_element(By.LINK_TEXT, "Click Here")

8. Locate by Partial Link Text

Method:find_element(By.PARTIAL_LINK_TEXT, "partial_link_text")

Description:Locate by a link's partial text content.

 element = driver.find_element(By.PARTIAL_LINK_TEXT, "Click")

Best Practices for Element Locating

Prioritize unique attributes:

  • Try to useid、nameand other unique attributes to locate elements.

Avoid using dynamic attributes:

  • If an element's attributes are dynamically generated (such as random IDs), avoid directly using these attributes for locating.

Use relative locating:

  • Use XPath or CSS selectors combined with the element's hierarchical relationships for locating.

Add waiting mechanisms:

  • Use implicit waits or explicit waits to ensure elements are fully loaded before performing operations.

Common Element Locating Methods

Selenium provides multiple element locating methods, each suitable for different scenarios. The following are common element locating methods:

1、find_element_by_id

find_element_by_idis by using the element'sidattribute to locate the element.idThis attribute is unique in HTML, so this method is usually the most direct and efficient.

Example

element = driver.find_element_by_id("element_id")

2、find_element_by_name

find_element_by_nameis by using the element'snameattribute to locate the element.nameThis attribute is very common in form elements.

Example

element = driver.find_element_by_name("element_name")

3、find_element_by_class_name

find_element_by_class_nameis by using the element'sclassattribute to locate the element.classThis attribute is usually used for style definitions, and multiple elements may share the sameclass。

Example

element = driver.find_element_by_class_name("element_class")

4、 find_element_by_tag_name

find_element_by_tag_nameis to locate elements by the element's tag name. Tag names such asdiv、input、aetc.

Example

element = driver.find_element_by_tag_name("tag_name")

5、 find_element_by_css_selector

find_element_by_css_selectoris to locate elements by CSS selectors. CSS selectors are very flexible and can combine multiple conditions.

Example

element = driver.find_element_by_css_selector("css_selector")

6、 find_element_by_xpath

find_element_by_xpathis to locate elements by XPath expressions. XPath is a language for locating nodes in XML documents, and it is very powerful.

Example

element = driver.find_element_by_xpath("xpath_expression")

7、 find_element_by_link_text

find_element_by_link_textis to locate elements by the link's text content. It is suitable for locating<a>tags.

Example

element = driver.find_element_by_link_text("link_text")

8、 find_element_by_partial_link_text

find_element_by_partial_link_textis to locate elements by partial text content of a link. It is suitable for scenarios where the text is long or needs partial matching.

Example

element = driver.find_element_by_partial_link_text("partial_link_text")

Locating multiple elements (find_elements)

Sometimes we need to locate multiple elements rather than a single element. Selenium providesfind_elementsmethod, which returns a list of elements.

Example

elements = driver.find_elements_by_class_name("element_class")

find_elementsThe method is the same as thefind_elementmethod in usage, except that it returns a list.


Tips for Locating Dynamic Elements

In web applications, some elements' attributes are dynamically generated and change every time the page is refreshed. When dealing with such dynamic elements, you can use the following techniques:

1. Use relative paths

In XPath or CSS selectors, use relative paths instead of absolute paths. Relative paths can avoid locating failures caused by changes in element positions.

Example

element = driver.find_element_by_xpath("//div[@class='dynamic_class']")

2. Use partial matching

For dynamically generatedidorclass, you can use partial matching to locate elements. For example, use thecontainsfunction.

Example

element = driver.find_element_by_xpath("//div[contains(@id, 'dynamic_part')]")

3. Use waiting mechanisms

Dynamic elements may not appear on the page immediately. You can use Selenium's waiting mechanisms to wait for elements to appear.

Example

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

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "dynamic_id"))
)

4. Use JavaScript for locating

In some cases, you can locate dynamic elements by executing JavaScript.

Example

element = driver.execute_script("return document.querySelector('dynamic_selector');")

Comprehensive Example

Selenium provides a rich set of element locating methods. Mastering these methods can help us locate page elements efficiently.

For dynamic elements, flexibly applying techniques such as relative paths, partial matching, waiting mechanisms, and JavaScript locating can greatly improve the stability and reliability of automated testing.

The following is a complete example showing how to use multiple locating methods to find elements and perform operations:

Example

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

# Start the browser
service = ChromeService(executable_path="./chromedriver")
driver = webdriver.Chrome(service=service)

# Open the web page
driver.get("https://www.example.com")

# Locate the input box by ID and enter text
username = driver.find_element(By.ID, "username")
username.send_keys("testuser")

# Locate the input box by Name and enter text
password = driver.find_element(By.NAME, "password")
password.send_keys("password123")

# Locate the button by CSS selector and click
submit_button = driver.find_element(By.CSS_SELECTOR, "button.submit-btn")
submit_button.click()

# Locate the link by XPath and click
link = driver.find_element(By.XPATH, "//a[text()='Click Here']")
link.click()

# Close the browser
driver.quit()
Other Extensions