繁体   English   中英

如何解决此错误:IndexError:列表索引超出范围

[英]How can I fix this error: IndexError: list index out of range

我正在抓取flipkart网站。 我需要在代码中进行哪些更改,以便该错误消失并打印出元素名称?

import requests
from bs4 import BeautifulSoup as soup
r=requests.get("https://www.flipkart.com/search?q=iphone&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off")
c=r.content
a=soup(c,"html.parser")
all=a.find_all("div",{"class":"bhgxx2 col-12-12"})
b=len(all)

print(all[1].find_all("div",{"class":"_3wU53n"})[1].get_text)

产量

Traceback (most recent call last):
  File "1.py", line 12, in <module>
    print(all[1].find_all("div",{"class":"_3wU53n"})[1].get_text)
IndexError: list index out of range

嗨Praneet,欢迎来到Stack Overflow!
我运行了您的代码,在我看来,您看到的是IndexError: list index out of range错误,因为BeautifulSoup实际上在HTML中找不到class=_3wU53n div ,因此返回一个空列表( [] )。 您可以将最后一行更改为:
print(all[1].find_all("div",{"class":"_3wU53n"})
由于列表为空,您显然无法访问其中的任何元素,因为没有元素。

print(all[1].find_all("div",{"class":"_3wU53n"})[1].get_text)将只给出索引0的一个值,而您使用索引1,这就是给出错误的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM