以下是RSS订阅的几行示例:
<rss version="2.0">
<channel>
<title>Hacker News</title><link>http://news.ycombinator.com/</link><description>Links for the intellectually curious, ranked by readers.</description>
<item>
<title>EFF Patent Project Gets Half-Million-Dollar Boost from Mark Cuban and 'Notch'</title>
<link>https://www.eff.org/press/releases/eff-patent-project-gets-half-million-dollar-boost-mark-cuban-and-notch</link>
<comments>http://news.ycombinator.com/item?id=4944322</comments>
<description><![CDATA[<a href="http://news.ycombinator.com/item?id=4944322">Comments</a>]]></description>
</item>
<item>
<title>Two Billion Pixel Photo of Mount Everest (can you find the climbers?)</title>
<link>https://s3.amazonaws.com/Gigapans/EBC_Pumori_050112_8bit_FLAT/EBC_Pumori_050112_8bit_FLAT.html</link>
<comments>http://news.ycombinator.com/item?id=4943361</comments>
<description><![CDATA[<a href="http://news.ycombinator.com/item?id=4943361">Comments</a>]]></description>
</item>
...
</channel>
</rss>
以下是我用Python编写的代码,用于访问此Feed并打印每个项目的标题
、链接
和评论
:
import sys
import requests
from bs4 import BeautifulSoup
request = requests.get('http://news.ycombinator.com/rss')
soup = BeautifulSoup(request.text)
items = soup.find_all('item')
for item in items:
title = item.find('title').text
link = item.find('link').text
comments = item.find('comments').text
print title + ' - ' + link + ' - ' + comments
然而,这个脚本输出的结果看起来像这样:
EFF Patent Project Gets Half-Million-Dollar Boost from Mark Cuban and 'Notch' - - http://news.ycombinator.com/item?id=4944322
Two Billion Pixel Photo of Mount Everest (can you find the climbers?) - - http://news.ycombinator.com/item?id=4943361
...
正如您所看到的,中间的项目
link
被省略了。也就是说,link
的结果值以某种方式成为空字符串。那是为什么呢?当我深入挖掘中的内容时,我意识到它在解析XML时出现了问题。这可以通过查看中的第一个项目来看出:
>>> print items[0]
<item><title>EFF Patent Project Gets Half-Million-Dollar Boost from Mark Cuban and 'Notch'</title></link>https://www.eff.org/press/releases/eff-patent-project-gets-half-million-dollar-boost-mark-cuban-and-notch<comments>http://news.ycombinator.com/item?id=4944322</comments><description>...</description></item>
你会注意到在`link`标签里出现了一些奇怪的东西。它只得到了关闭标签,然后是该标签后面的文本。这是一些非常奇怪的行为,特别是与`title`和`comments`不出问题相比较。这似乎是BeautifulSoup的问题,因为requests实际读入的内容没有任何问题。我认为这不仅限于BeautifulSoup,因为我也尝试使用xml.etree.ElementTree API,但是出现了同样的问题(BeautifulSoup是基于此API构建的吗?)。有人知道为什么会发生这种情况,或者我如何在不出错的情况下继续使用BeautifulSoup吗?注意:我最终能够通过xml.dom.minidom得到我想要的结果,但这似乎不是一个高度推荐的库。如果可能的话,我想继续使用BeautifulSoup。更新:我在使用Python 2.7.2和BS4 4.1.3的OSX 10.8 Mac上。更新2:我有lxml,并且使用pip安装。它的版本是3.0.2。至于libxml,在/usr/lib中检查,显示的是libxml2.2.dylib。不确定这是何时或如何安装的。
ElementTree
、cElementTree
和lxml
实现进行了测试,它们都可以很好地获取到link
节点。所以,要么你在使用xml.etree.ElementTree
时出了问题,要么你没有提供正确的输入数据。 - abarnert/usr/lib/libxml2.2.dylib
,那么那个版本是多少,如何安装的? - abarnert