AttributeError: 'list' object has no attribute 'get_attribute'
错误说明您试图在 Python 中的列表上调用 get_attribute,但它应该是一个 Web 元素。
记住find_elements(复数)在Python-Selenium 绑定 中返回一个列表。 find_element 在 Python-Selenium 绑定
中返回一个 Web 元素
问题解决方案:
- 在大多数情况下,更改为 find_element 应该可以解决问题。
所以,而不是
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"))