Home >Backend Development >Python Tutorial >How to Locate Elements by Class Attribute Using Selenium's EC.presence_of_element_located?

How to Locate Elements by Class Attribute Using Selenium's EC.presence_of_element_located?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 16:20:11901browse

How to Locate Elements by Class Attribute Using Selenium's EC.presence_of_element_located?

How to Use EC.presence_of_element_located with Class Attribute

When using selenium's EC.presence_of_element_located method with WebDriverWait, you canspecify an element to find by its class attribute instead of its ID. Here's how to do it:

The original code:

element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.ID, "tabla_evolucion")))

attempts to find an element by its ID. To find an element by its class instead, change "By.ID" to "By.CLASS" and provide the class name:

element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.CLASS, "ng-binding ng-scope")))

Note: Avoid using presence_of_element_located for interactive actions. Instead, prefer visibility_of_element_located or element_to_be_clickable.

Additionally:

  • Using CSS_SELECTOR or XPATH allows you to combine ID and class attributes for more precise element location:
# CSS_SELECTOR
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
    (By.CSS_SELECTOR, ".ng-binding.ng-scope#tabla_evolucion")))

# XPATH
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
    (By.XPATH, "//*[@class='ng-binding ng-scope' and @id='tabla_evolucion']")))
  • Remember, compound class names are not permitted in By.class. The above code attempts to find an element with both "ng-binding" and "ng-scope" classes.

The above is the detailed content of How to Locate Elements by Class Attribute Using Selenium's EC.presence_of_element_located?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn