【问题标题】:Attribute raises NoSuchElementException in selenium Python属性在 selenium Python 中引发 NoSuchElementException
【发布时间】:2020-04-07 21:45:05
【问题描述】:

我可以获取属性包含X 的元素,但我无法获取属性本身。为什么?

此代码不会引发任何错误:

links = browser.find_elements_by_xpath('//div[@aria-label="Conversations"]//a[contains(@data-href, "https://www.messenger.com/t/")]')

此代码引发NoSuchElementException 错误:

links = browser.find_elements_by_xpath('//div[@aria-label="Conversations"]//a[contains(@data-href, "https://www.messenger.com/t/")]/@data-href')

此代码是从带有聊天的 Messenger 主页中提取的。我想获取ul 列表中的所有链接... 我不明白...请帮忙?

【问题讨论】:

  • 您是否尝试等待元素?

标签: python-3.x selenium attributes nosuchelementexception


【解决方案1】:

要获取所有链接数据-href 值,您需要遍历链接元素并使用get_attribute()

links = browser.find_elements_by_xpath('//div[@aria-label="Conversations"]//a[contains(@data-href, "https://www.messenger.com/t/")]')
ul_list=[link.get_attribute("data-href") for link in links]
print(ul_list)

【讨论】:

  • 我在代码之后使用了 get_attribute("data-href") 并且它不起作用,在这里它可以工作,谢谢!
  • 很高兴知道它有效。如果这对未来的读者有帮助,请为答案投票。谢谢!
【解决方案2】:
wait = WebDriverWait(driver, 20)
lists=wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@aria-label="Conversations"]//a[contains(@data-href, "https://www.messenger.com/t/")]/@data-href')))
 for element in lists:
      print element.text

注意:将以下导入添加到您的解决方案中

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

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2023-03-27
    • 2023-03-10
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多