Selenium Finding elements by class name in python

后端 未结 5 491
清酒与你
清酒与你 2020-12-14 06:05

How can I filter elements which having a same class?


 
  

Link1.

<
5条回答
  •  死守一世寂寞
    2020-12-14 06:13

    As per the HTML:

    
        
        

    Link1.

    Link2.

    Two(2)

    elements are having the same class content.

    So to filter the elements having the same class i.e. content and create a list you can use either of the following Locator Strategies:

    • Using class_name:

      elements = driver.find_elements_by_class_name("content")
      
    • Using css_selector:

       elements = driver.find_elements_by_css_selector(".content")
      
    • Using xpath:

      elements = driver.find_elements_by_xpath("//*[@class='content']")
      

    Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

    • Using CLASS_NAME:

      elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
      
    • Using CSS_SELECTOR:

      elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
      
    • Using XPATH:

      elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
      
    • Note : You have to add the following imports :

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

    References

    You can find a couple of relevant discussions in:

    • How to identify an element through classname even though there are multiple elements with the same classnames using Selenium and Python
    • Unable to locate element using className in Selenium and Java
    • What are properties of find_element_by_class_name in selenium python?
    • How to locate the last web element using classname attribute through Selenium and Python

提交回复
热议问题