我正在尝试 刮 来自 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/