我在此代码中收到IndexError,您能帮我吗?

时间:2020-06-07 08:25:44

标签: python

在加载此代码时:

import bs4 
from urllib.request import urlopen as req
from bs4 import BeautifulSoup as soup 
my_url = "https://www.daraz.com.np"
uclient = req(my_url)
page_html = uclient.read()
uclient.close()
page_soup = soup(page_html, "html.parser")
container = page_soup.findAll("div",{"class":"c3e8SH"})
len(container)
container[0]

我遇到了这个错误

Traceback (most recent call last):
  File "C:\Users\bhatt\my_scrap.py", line 11, in <module>
    container[0]
IndexError: list index out of range

2 个答案:

答案 0 :(得分:1)

问题是container = page_soup.findAll("div",{"class":"c3e8SH"})导致一个空列表。
如果容器列表不为空,则可以尝试添加条件,然后将第一个元素作为

container[0] if container else None #or another part that you want to execute in case the container list is empty

以克服此错误。

答案 1 :(得分:0)

container = page_soup.findAll("div",{"class":"c3e8SH"})似乎是一个空列表, 表示没有元素具有c3e8SH类。