在Python中运行基本Web Scrape时出现索引错误

2024-05-29 04:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7。当我试图运行这段代码时,当函数命中print findPatTitle[I]时,遇到了一个问题,python返回“Index Error:list Index out out range”。我从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"

Tags: 代码fromimportreindexrangeouturlopen
1条回答
网友
1楼 · 发布于 2024-05-29 04:22:54

如果regex成功地找到了title和link标记,那么在使用findall时将得到一个匹配字符串的列表。在这种情况下,您可以遍历它们并打印它。在

比如:

for title in findPatTitle:
    print title

for link in findPatLink:
    print link

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

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

^{pr2}$

相关问题 更多 >

    热门问题