python - 索引错误 : list index out of range/AttributeError: 'list' object has no attribute 'get_attribute'

标签 python selenium selenium-webdriver web-scraping instagram

enter image description here
我正在尝试 来自 Instagram 的喜欢/浏览。但是出现以下错误:
索引错误:列表索引超出范围:--- when i try viewcth[0].get_attribute('innerHTML')AttributeError: 'list' 对象没有属性 'get_attribute' :--- 当我尝试时 viewct = viewcth.get_attribute('innerHTML')代码:

viewcth = bdy.find_elements_by_xpath(".//*[@class='eo2As ']//*[@class='EDfFK ygqzn']//*[@class='Nm9Fw']")
if (len(viewcth) != 0):
    viewct = viewcth[0].get_attribute('innerText')
else:
    viewcth = bdy.find_elements_by_xpath(".//*[@class='eo2As ']//*[@class='HbPOm _9Ytll']//*[@class='vcOH2']")
    # viewct = viewcth.get_attribute('innerHTML')
    viewct = viewcth[0].get_attribute('innerHTML')
pagedict['viewcount'] = viewct
print("Viewct is " + viewct)

最佳答案

您使用了错误的定位器。
这就是为什么viewcth是和空列表。find_elements_by_xpath(".//*[@class='eo2As ']//*[@class='EDfFK ygqzn']//*[@class='Nm9Fw']")找不到匹配的元素并返回空列表。
因此,当您尝试通过 viewcth[0] 从该列表中获取第一个元素时你得到

IndexError: list index out of range.


如果您尝试执行 viewct = viewcth.get_attribute('innerHTML')这给了你

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


viewcth是一个列表。空的,但仍然是一个列表。
所以你不能申请.get_attribute('innerHTML')列表上的方法,它不是网络元素。
如果你想获得像这样的数量,试试这个:
对于图像
likes = bdy.find_element_by_xpath(".//a[@class='zV_Nj']/span").text
对于视频:
likes = bdy.find_element_by_xpath(".//div[@class='Nm9Fw']/a").text
或者
likes = bdy.find_element_by_xpath(".//div[@class='HbPOm _9Ytll']/span").text

关于python - 索引错误 : list index out of range/AttributeError: 'list' object has no attribute 'get_attribute' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68270921/

相关文章:

python - 无法使用selenium python找到信用卡号码的元素

python - 用于生成具有特定属性的唯一元组列表的算法

python-2.7 - XPath 和 Selenium 问题

java - 多表 td 元素的 Xpath

python - 用于定位文本区域元素的 Selenium 脚本不起作用

java - "Next"Button in Javascript & used JavascriptExecutor to click on "next"button 但它没有帮助我

python - 我在 Firestore 中执行了多少次读取?

javascript - 通过 POST 将 JSON 从 Flask 返回到 AJAX

Python 嵌入 C++ : ImportError: No module named pyfunction

java - 如何有效地在selenium中长时间等待