我使用的是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"
如果regex成功地找到了title和link标记,那么在使用findall时将得到一个匹配字符串的列表。在这种情况下,您可以遍历它们并打印它。在
比如:
您得到的索引错误是因为您试图访问从2到16的元素列表,而标题或链接中没有16个元素。在
注意,
^{pr2}$listIterator[:] = range(2,16)
不是为此编写代码的好方法。你可以用相关问题 更多 >
编程相关推荐