【问题标题】:Index Error When Running Basic Web Scrape in Python在 Python 中运行基本 Web 抓取时出现索引错误
【发布时间】:2011-09-06 03:27:03
【问题描述】:

我使用的是 Python 2.7。当我尝试运行此代码时,当函数命中 print findPatTitle[i] 时出现问题,并且 python 返回“索引错误:列表索引超出范围”。我从 youtube 上的第 13 个 python 教程中获取这段代码,我很确定代码是相同的,所以我不明白为什么我会遇到范围问题。有什么想法吗?

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read()

patFinderTitle = re.compile('<title>(.*)<title>')

patFinderLink = re.compile('<link rel.*href="(.*)" />')

findPatTitle = re.findall(patFinderTitle,webpage)
findPatLink = re.findall(patFinderLink,webpage)

listIterator = []
listIterator[:] = range(2,16)

for i in listIterator:
    print findPatTitle[i]
    print findPatLink[i]
    print "\n"

【问题讨论】:

标签: python beautifulsoup web-scraping


【解决方案1】:

如果您正则表达式设法找出标题和链接标签,您将在使用 findall 时获得匹配字符串的列表。在这种情况下,您可以遍历它们并打印它。

喜欢:

for title in findPatTitle:
    print title

for link in findPatLink:
    print link

您得到的索引错误是因为您试图访问从 2 到 16 的元素列表,并且标题或链接中没有 16 个元素。

注意,listIterator[:] = range(2,16) 不是为此目的编写代码的好方法。你可以使用

for i in range(2, 16)
    # use i

【讨论】:

  • 感谢您的提示。我的代码有问题,findPatTitle 应该是 (.*)。对此感到抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 2016-12-04
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
相关资源
最近更新 更多