名称错误:未定义名称“re”

2024-09-28 21:55:31 发布

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

我对python很陌生。很新。我从教程中复制了以下内容

#!/usr/bin/python

from urllib import urlopen
from BeautifulSoup import BeautifulSoup

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"

我知道错误:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    patFinderTitle = re.compile('<title>(.*)</title>')
NameError: name 're' is not defined

我做错什么了?


Tags: fromimportretitleurlopenprintcompilewebpage
2条回答

除了丢失的import re,您的程序还有另一个错误。在

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

在行尾的read之后,您将()关闭。所以目前webpage是对.read方法的引用,它不是.read()调用的结果。

您需要在代码中导入regular expression module

import re
re.compile('<title>(.*)</title>')

相关问题 更多 >