[英]How can I fix this error: IndexError: list index out of range
I'm scraping the flipkart website. 我正在抓取flipkart网站。 What changes do I need to make in the code so that this error is gone and the element name will be printed?
我需要在代码中进行哪些更改,以便该错误消失并打印出元素名称?
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)
output 产量
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
Hi Praneet and welcome to Stack Overflow! 嗨Praneet,欢迎来到Stack Overflow!
I ran your code and it seems to me that you're seeing the IndexError: list index out of range
error because BeautifulSoup
actually can't find aa div
with class=_3wU53n
in the HTML and therefore returns an empty list ( []
). 我运行了您的代码,在我看来,您看到的是
IndexError: list index out of range
错误,因为BeautifulSoup
实际上在HTML中找不到class=_3wU53n
div
,因此返回一个空列表( []
)。 You can check for yourself by changing your last line to: 您可以将最后一行更改为:
print(all[1].find_all("div",{"class":"_3wU53n"})
Since the list is empty you obviously can't access any element in it since there are none. 由于列表为空,您显然无法访问其中的任何元素,因为没有元素。
print(all[1].find_all("div",{"class":"_3wU53n"})[1].get_text)
将只给出索引0的一个值,而您使用索引1,这就是给出错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.