AttributeError:'list'对象没有属性'get\u attribute'

2024-09-30 03:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一部分代码,并希望收到我在“统计信息链接”中找到的元素的链接。 但它给了我一个错误,并写道:

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

下面是包含JS元素http://www.ukrstat.gov.ua/head.html的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)

谢谢你的帮助


Tags: text信息http元素get链接htmlwww
2条回答
AttributeError: 'list' object has no attribute 'get_attribute'

该错误说明您试图在Python中调用列表上的get_attribute,但它应该是一个web元素

记住find_elements(复数)在Python Selenium绑定中返回一个列表。其中asfind_elementPython Selenium绑定中返回一个web元素

问题解决方案:

  1. 在大多数情况下,更改find_元素应该可以解决问题

因此,与其

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

这样做:

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"))

由于您正在给browser.find_elements,它将返回列表中的元素。您可以对一个WebElement使用.get_attribute,而不是列出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"))

相关问题 更多 >

    热门问题