如何使用没有值的属性查找页面上的每个元素?

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

示例代码

<a href="/cristiano/" title="cristiano">\<span class="\_7UhW9   xLCgt        qyrsm KV-D4           se6yk       T0kll "\>cristiano\</span\></a>

如何告诉 python 找到带有 classtitle、[=18= 的每个元素]href 和 tabindex 属性。然后获取每个的“标题”值。

尝试了find_element_by_xpath但没有结果

语法是"//*[@attribute_name]"
要获取具有 title 属性的所有元素,XPath 是 "//*[@title]"
要获取具有 class 属性的所有元素,XPath 是 "//*[@class]"
要获取具有 href 属性的所有元素,XPath 是 "//*[@href]"
等等
因此,要从页面上的所有元素中获取所有 title 属性值,您可以这样做:

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

等等
如果你想定位所有具有 title and class and href 属性的元素,所有的3 个,看起来像这样:

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)

查找具有 classtitlehref 和textract 您可以使用的每个项目的 title 属性的值 you can use either of the following :

  • 使用 xpath:

    print([my_elem.get_attribute("title") for my_elem in driver.find_elements(By.XPATH, "//a[@href and @title][.//span[@class and text()]]")])
    
  • 诱导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()]]")))])
    
  • 注意:您必须添加以下导入:

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