属性错误:"列表"对象没有属性"get_attribute"



我有这样的一部分代码,并希望接收我在"statistic_info_link"中找到的元素的链接。但是它给了我错误,写:

AttributeError: 'list' object没有属性'get_attribute'

这里是结构的html页面与JS元素http://www.ukrstat.gov.ua/head.html因此,我需要找到写有"统计信息"-"Статистична інформація"的链接

r = requests.get("http://www.ukrstat.gov.ua/") 
soup = BeautifulSoup(r.text) 
head=soup.find('frame',{'name': 'banner'})
#Recieve link on head
link_head='http://www.ukrstat.gov.ua/'+head.get('src')
browser.get(link_head)
statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]").get_attribute("outerHTML")
print(statistic_info_link)

谢谢你的帮助!

既然你给browser.find_elements它返回元素在列表。你可以用.get_attribute来表示一个WebElement,而不是一个WebElement列表。

statistic_info_link = browser.find_elements改为

statistic_info_link = browser.find_element...

或者遍历列表

statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]")
for ele in statistic_info_link:
print(ele.get_attribute("outerHTML"))
AttributeError: 'list' object has no attribute 'get_attribute'

这个错误解释了你正在尝试在Python中调用列表get_attribute,但它应该是一个web元素。

记住find_elements(复数)在Python-Selenium绑定中返回一个列表。当find_element返回一个web元素在Python-Selenium bindings

问题解决方案:

  1. 在大多数情况下,更改为find_element应该解决问题。

所以,代替

statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]").get_attribute("outerHTML")
print(statistic_info_link)

do this:

statistic_info_link = browser.find_element_by_xpath("//*[contains(text(), 'Статистична інформація')]").get_attribute("innerHTML")
print(statistic_info_link)

另外,我不太确定outerHTML,因此我已将其更改为innerHTML

第二次修复:

使用列表索引:

statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]")[0].get_attribute("outerHTML")
print(statistic_info_link)

statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]")[0].get_attribute("innerHTML")
print(statistic_info_link)

最后,如果你真的想从列表中提取文本,请使用下面的代码:

statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]").get_attribute("outerHTML")
for ele in statistic_info_link :
print(ele.get_attribute("outerHTML"))

statistic_info_link = browser.find_elements_by_xpath("//*[contains(text(), 'Статистична інформація')]").get_attribute("outerHTML")
for ele in statistic_info_link :
print(ele.get_attribute("innerHTML"))

最新更新