[英]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.