Python 如何修复此错误:索引器错误:列表索引超出范围
我正在浏览flipkart网站。我需要在代码中做哪些更改,以消除此错误并打印元素名称Python 如何修复此错误:索引器错误:列表索引超出范围,python,python-3.7,Python,Python 3.7,我正在浏览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=
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)
输出
回溯(最近一次呼叫最后一次):
文件“1.py”,第12行,在
打印(所有[1]。查找所有(“div”,“class”:“\u3wu53n”})[1]。获取文本)
索引器:列表索引超出范围
print(all[1]。find_all(“div”,“class”:“\u 3wU53n”})[1]。get_text)
将只给出索引0的一个值,您使用索引1,这就是它给出错误的原因。大家好,欢迎使用堆栈溢出我运行了您的代码,在我看来,您似乎看到了
索引器:列表索引超出范围的错误,因为BeautifulSoup
实际上无法在HTML中找到带有class=\u3wu53n
的div
,因此返回一个空列表([]
)。
您可以将最后一行更改为:
print(all[1]。查找所有(“div”,“class”:“\u3wu53n”})
由于列表为空,您显然无法访问其中的任何元素,因为其中没有任何元素
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