Home > OS >  How to find every element on page using attributes without values?
How to find every element on page using attributes without values?

Time:03-23

Example code ``` <span >cristiano</span>

How to tell python to find every element with *class*, *title*, *href*, and *tabindex* attributes. Then get the "title" value for each.

tried find_element_by_xpath but no result

CodePudding user response:

The syntax is "//*[@attribute_name]" i.e.
to get all the elements with title attribute the XPath is "//*[@title]",
to get all the elements with class attribute the XPath is "//*[@class]",
to get all the elements with href attribute the XPath is "//*[@href]"
etc.
So, to get all the title attribute values from all the elements on the page you can do something like this:

elements = driver.find_elements(By.XPATH, "//*[@title]")
for element in elements:
    title = element.get_attribute("title")
    print(title)

etc.
In case you want to locate all elements having title and class and href attributes, all the 3 in each all of them, it will look like this:

elements = driver.find_elements(By.XPATH, "//*[@title and @class and @href]")
for element in elements:
    title_val = element.get_attribute("title")
    class_val = element.get_attribute("class")
    href_val = element.get_attribute("href")
    print(title_val)
    print(class_val)
    print(href_val)

CodePudding user response:

To find every element with class, title, href and textract the value of the title attribute for each of the items you can use list comprehension you can use either of the following locator strategies:

  • Using xpath:

    print([my_elem.get_attribute("title") for my_elem in driver.find_elements(By.XPATH, "//a[@href and @title][.//span[@class and text()]]")])
    
  • Inducing WebDriverWait:

    print([my_elem.get_attribute("title") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[@href and @title][.//span[@class and text()]]")))])
    
  • 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
    
  • Related