使用urllib2进行Web报废

2024-06-17 10:22:57 发布

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

我正在尝试取消此RSS源的所有标题:

http://www.quora.com/Python-programming-language-1/rss

这是我的代码:

import urllib2
import re
content = urllib2.urlopen('http://www.quora.com/Python-programming-language-1/rss').read()
allTitles =  re.compile('<title>(.*)</title>')
list = re.findall(allTitles,content)
for e in range(0, 2):
    print list[e]

然而,我没有得到标题列表作为输出,而是从rss源代码中获取了一堆代码。我做错什么了?在


Tags: 代码importrecomhttp标题titlewww
2条回答

你应该用贪婪的标记吗在表达式中:

#allTitles =  re.compile('<title>(.*)</title>')
allTitles =  re.compile('<title>(.*?)</title>')

没有?除最后一个</title>之外的所有文本都放在(.*)组中。。。在

如前所述,您的代码缺少regexp的贪婪说明符,可以用它来修复。但我强烈建议从正则表达式切换到更适合xml解析的工具,比如lxmlBeautifulSoup或专门的rss解析模块,如feedparser。在

例如,查看如何使用lxml完成任务:

>>> import lxml.etree
>>> rss = lxml.etree.fromstring(content)
>>> titles = rss.findall('.//title')
>>> print '\n'.join(title.text for title in titles[:2])
Questions About Python (programming language) on Quora
Could someone explain for me the following Python function that uses @wraps from functools?

相关问题 更多 >