简体   繁体   中英

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

I'm scraping the flipkart website. 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!
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 ( [] ). 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,这就是给出错误的原因。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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