IndexError:使用jupyter笔记本时,列表索引超出范围

时间:2018-07-10 12:37:14

标签: python indexing index-error

# Find all course summaries
summaries = soup.find_all("div", class_="course-summary-card")
summaries[0]

输出: enter image description here

 IndexError                                Traceback (most recent call last)
    <ipython-input-62-01693c759680> in <module>()
          1 # Find all course summaries
          2 summaries = soup.find_all("div", class_="course-summary-card")
    ----> 3 summaries[0]

    IndexError: list index out of range

2 个答案:

答案 0 :(得分:3)

如果summaries[0]超出范围,则summaries必须为空列表。这是因为您的课程摘要中没有"div"

答案 1 :(得分:1)

这意味着summaries是一个空列表。您可以使用len()

这里是您的问题的示例:

>>> s=[]
>>> len(s)
0
>>> s[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

然后,您可以仅使用if来检查列表是否为空:

>>> s=[]
>>> if s: 
...     print 'ok'
... 
>>> s=[1]
>>> if s: 
...     print 'ok'
... 
ok