AttributeError: 'list' object has no attribute 'text' error finding elements within DOM

AttributeError: 'list' object has no attribute 'text' error finding elements within DOM

我尝试在树中查找元素 DOM 但我遇到了问题。我写:

age = browser.find_elements_by_xpath("//div[@id='ads']/ul/li[6]/span[2]").text

但它一直显示我的错误:

AttributeError: 'list' object has no attribute 'text'

怎么了?

如果您只想从一个元素中获取文本,请使用 find_element 而不是 find_elements

age = browser.find_element_by_xpath("//div[@id='ads']/ul/li[6]/span[2]").text

find_elements 将为您提供 list 个元素,要获取每个元素的文本,您必须遍历结果:

for element in browser.find_elements_by_xpath("//div[@id='ads']/ul/li[6]/span[2]"):
    element.text

find_elements* returns a list 其中 text.


解决方案

您需要使用 find_element_by_xpath() 而不是 find_elements_by_xpath()。实际上,您的代码行将是:

age = browser.find_element_by_xpath("//div[@id='ads']/ul/li[6]/span[2]").text