【问题标题】:print(icerik[0].text) IndexError: list index out of range errorprint(icerik[0].text) IndexError: 列表索引超出范围错误
【发布时间】:2018-07-31 08:18:15
【问题描述】:
from bs4 import BeautifulSoup
import urllib.request
url = "http://www.python.tc/python-nedir"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'single-post-content'})
print(icerik[0].text)

Traceback (most recent call last):
  File "C:\Users\hira\AppData\Local\Programs\Python\Python35\d.py", line 11, in <module>
    print(icerik[0].text)
IndexError: list index out of range

【问题讨论】:

  • 您能否提供比 sn-p 代码和错误消息更多的信息?因为就目前而言,这里没有要回答的问题,只说明显而易见的:icerik 显然是一个空列表,因为您的 find_all 没有找到任何东西......
  • 如何拉取网站内容?

标签: python beautifulsoup urllib


【解决方案1】:

查看源代码,页面不包含&lt;div&gt;single-post-content。要获取帖子内容,请尝试获取&lt;article&gt;标签:

from bs4 import BeautifulSoup
import urllib.request
url = "http://www.python.tc/python-nedir"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')

icerik = soup.find('article',attrs={'class':'single-post'})
print(icerik.text)

这将打印:

Python Nedir?               
  Ali Yaman  Yenilmez Mayıs 5, 2016 Programlama , Temel Programlama 14 Yorumlar 994 görüntüleme Python Dili Nedir? Python, Guido Van rossum adlı hollandalı bir programcı tarafından yazılmış bir programlama dilidir. Geliştirilmesine 1990 yılında başlayan Python; C ve C++ gibi programlama dillerine...

...and so on.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2018-04-22
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多