Beautifulsoup内容返回列表索引超出范围

0 投票
2 回答
582 浏览
提问于 2025-04-18 09:15

我在看这些教程 http://importpython.blogspot.com/2009/12/how-to-get-beautifulsoup-to-filter.htmlhttp://importpython.blogspot.com/2009/12/how-to-screen-scrape-craigslist-using.html,但是即使是复制粘贴的代码,我也无法打印出链接的标题,因为在第11行和第8行我遇到了“列表索引超出范围”的错误。如果我只是复制粘贴代码,为什么会出错呢?我尝试了其他变体,比如只返回链接,这样完全没问题,所以我觉得这不是本地的问题。

编辑

问题出在以下代码(来自 http://importpython.blogspot.com/2009/12/how-to-screen-scrape-craigslist-using.html):

from BeautifulSoup import BeautifulSoup   #1
from urllib2 import urlopen               #2

site = "http://sfbay.craigslist.org/rea/" #3
html = urlopen(site)                      #4
soup = BeautifulSoup(html)                #5
postings = soup('p')                      #6

for post in postings:                     #7
    print post('a')[0].contents[0]        #8
    print post('a')[0]['href']            #9

导致的错误是:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

相关问题:

2 个回答

0

BeautifulSoup 是一个非常强大的工具……所以别偷懒,充分利用它的功能:

soup = BeautifulSoup(html)
postings = soup.find_all('p', {'class': 'row'})

for post in postings:
   info_container = post.find('span', {'class':'pl'}).find('a')
   print info_container.text
   print info_container['href']

我总是尽量避免在代码中写死数组的大小。 而且使用 find 函数会更直观。

0

这段话是说,这个代码是依赖于Craigslist网站的HTML结构,但这个结构已经发生了变化。所以你在第二个'a'标签里才能得到你想要的“正确”结果:

print post('a')[1].contents[0]
print post('a')[1]['href'] 

撰写回答