YCombinator 足够好,可以提供RSS feed and a 大RSS提要包含顶部项目黑客新闻。我正在尝试编写一个 python 脚本来访问 RSS feed 文档,然后使用 BeautifulSoup 解析出某些信息。但是,当 BeautifulSoup 尝试获取每个项目的内容时,我遇到了一些奇怪的行为。
以下是 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)来访问此提要并打印出title
, link
, and comments
对于每个项目:
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
不知何故是一个空字符串。那么这是为什么呢?
当我深入研究其中的内容时soup
,我意识到它在解析 XML 时有点令人窒息。这可以通过查看第一项来看出items
:
>>> 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
and comments
被解析没有问题。
这似乎是 BeautifulSoup 的问题,因为请求实际读取的内容没有任何问题。我不认为它仅限于 BeautifulSoup,因为我也尝试使用 xml.etree.ElementTree API 并且出现了同样的问题(BeautifulSoup 是基于这个 API 构建的吗?)。
有谁知道为什么会发生这种情况,或者我如何仍然可以使用 BeautifulSoup 而不会出现此错误?
注意:我终于能够通过 xml.dom.minidom 获得我想要的东西,但这似乎不是一个强烈推荐的库。如果可能的话我想继续使用BeautifulSoup。
Update:我使用的是 OSX 10.8、Python 2.7.2 和 BS4 4.1.3 的 Mac。
Update 2:我有 lxml,它是用 pip 安装的。它是3.0.2版本。至于libxml,我检查了/usr/lib,显示的是libxml2.2.dylib。不确定何时或如何安装的。