为什么BeautifulSoup无法正确读取/解析这个RSS(XML)文档?

2023-11-22

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 &#39;Notch&#39;</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 &#39;Notch&#39; -  - 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 &#39;Notch&#39;</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版本。至于lib​​xml,我检查了/usr/lib,显示的是libxml2.2.dylib。不确定何时或如何安装的。


哇,好问题。在我看来,这是 BeautifulSoup 中的一个错误。您无法使用以下方式访问链接的原因soup.find_all('item').link是当你第一次将 html 加载到 BeautifulSoup 时,它对 HTML 做了一些奇怪的事情:

>>> from bs4 import BeautifulSoup as BS
>>> BS(html)
<html><body><rss version="2.0">
<channel>
<title>Hacker News</title><link/>http://news.ycombinator.com/<description>Links
for the intellectually curious, ranked by readers.</description>
<item>
<title>EFF Patent Project Gets Half-Million-Dollar Boost from Mark Cuban and 'No
tch'</title>
<link/>https://www.eff.org/press/releases/eff-patent-project-gets-half-million-d
ollar-boost-mark-cuban-and-notch
    <comments>http://news.ycombinator.com/item?id=4944322</comments>
<description>Comments]]&gt;</description>
</item>
<item>
<title>Two Billion Pixel Photo of Mount Everest (can you find the climbers?)</ti
tle>
<link/>https://s3.amazonaws.com/Gigapans/EBC_Pumori_050112_8bit_FLAT/EBC_Pumori_
050112_8bit_FLAT.html
    <comments>http://news.ycombinator.com/item?id=4943361</comments>
<description>Comments]]&gt;</description>
</item>
...
</channel>
</rss></body></html>

仔细一看,居然改变了第一个<link> tag to <link/>然后删除了</link>标签。我不确定为什么会这样做,但没有解决问题BeautifulSoup.BeautifulSoup类初始化,您现在无法使用它。

Update:

我认为你现在最好的(尽管是 hack-y)的选择是使用以下内容link:

>>> soup.find('item').link.next_sibling
u'http://news.ycombinator.com/'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么BeautifulSoup无法正确读取/解析这个RSS(XML)文档? 的相关文章

  • 优化完美平方问题,类似于Python中的硬币找零

    我这里有一个硬币兑换的解决方案 python 中的 leetcode 硬币兑换 https stackoverflow com questions 69517078 coin change leetcode in python 因为完全平方
  • 如何修复 Apache mod_wsgi 的 Python 版本不匹配问题?

    我收到此错误 Thu Jul 12 14 31 36 2012 error python init Python version mismatch expected 2 6 7 found 2 6 8 当尝试启动 Apache 服务器时 在
  • Pandas 字符串提取所有匹配项

    我正在学习 pandas 系列字符串方法中的正则表达式操作 我能够从字符串中提取第一个数字 但我的正则表达式与第二个数字不匹配 如何捕获这两个数字 注意第二行 第二个元素在这里是 NAN CODE import pandas as pd d
  • 如何忽略传递给函数的意外关键字参数?

    假设我有一些功能 f def f a None print a 现在 如果我有一本字典 比如dct a Foo 我可以打电话f dct 并得到结果Foo打印 但是 假设我有一本字典dct2 a Foo b Bar 如果我打电话f dct2
  • 重新索引错误没有意义

    I have DataFrames大小在 100k 到 2m 之间 我正在处理这个问题的框架是如此之大 但请注意 我必须对其他框架执行相同的操作 gt gt gt len data 357451 现在这个文件是通过编译许多文件创建的 所以它
  • Python sqlite3参数化删除表

    我在 python 中删除 sqlite3 表时遇到问题 我正在使用标准sqlite3模块 self conn sqlite3 connect sql drop table self conn execute sql u table nam
  • 在 Python 中绘制分类数据的三个维度

    我的数据包含三个我试图可视化的分类变量 城市 五个之一 职业 四种之一 血型 四种之一 到目前为止 我已经成功地以一种我认为易于使用的方式对数据进行了分组 import numpy as np pandas as pd Make data
  • 使用 Pymongo 从 Windows 连接到 AWS 实例上的 MongoDB

    此行反复抛出错误 client MongoClient ec2 12 345 67 89 us east 2 compute amazonaws com 27017 ssl True ssl keyfile C mongo pem 由于显而
  • Django 未在 404 页面上应用应用程序中的 CSS 文件

    姜戈3 0 8 Python 3 7 x 我有一个包含一些应用程序的 Django 项目 我正在尝试为 400 403 404 500 错误制作一些 默认 错误页面 我已经这样做了 并显示了适当的模板 但没有任何样式或 JS 在 404 错
  • 如何在Python中求和

    我想知道如何在 python 中表示总和而不需要像这样的循环here http docs scipy org doc scipy reference tutorial optimize html 我们有 def rosen x The Ro
  • 如何使用 xlrd 将新列和行添加到 .xls 文件

    如何向 xlrd 中的工作表添加新列和 或行 我有一个使用 open workbook 读取的 xls 文件 我需要在第一张表中添加一个新列 bouncebacks 然后在该表中添加新行 但我在 xlrd 文档中找不到任何显示如何添加新行和
  • 是否有更矢量化的方法来沿轴执行 numpy.outer ?

    gt gt gt x np array a0 a1 b0 b1 gt gt gt y np array x0 x1 y0 y1 gt gt gt iterable np outer x i y i for i in xrange x sha
  • USSD 接口 -> java web 应用程序通信

    请需要一些有关通过 USSD 接口进行 Java Web 应用程序通信的信息 我们需要实施这一举措 以覆盖拥有低端手机的贫困社区的目标客户群 我正在研究 USSD 作为与我们当前的 Java EE Web 应用程序进行通信的一种方式 我相信
  • 在python中安装scipy模块时出错

    我正在尝试使用 pip 在 python 中安装 scipy 模块 它显示以下错误 Command c users sony appdata local programs python python35 32 python exe u c
  • 如何加速 pandas 字符串函数?

    我正在使用 pandas 矢量化 str split 方法来提取从 上的拆分 返回的第一个元素 我还尝试使用 df apply 与 lambda 和 str split 来产生等效的结果 使用 timeit 时 我发现 df apply 的
  • Scrapy的redirect_urls异常.KeyError

    我是 Scrapy 和 Python 的新手 最近推出了我的第一个蜘蛛 有一个功能似乎以前有效 但现在它只适用于我试图废弃的一些网站 代码行是 item url direct response request meta redirect u
  • Python 队列 get()/task_done() 问题

    我的消费者端队列 m queue get queue task done
  • 如何保持 python 3 脚本 (Bot) 运行

    不是母语英语 抱歉 英语可能很蹩脚 我也是编程新手 您好 我正在尝试使用 QueryServer 连接到 TeamSpeak 服务器来创建机器人 经过几天的努力 它有效 只有 1 个问题 而我却被这个问题困扰了 如果您需要检查 这是我正在使
  • Flask 扩展未在 app.extensions 中注册

    我想访问在我的 Flask 应用程序上注册的一些扩展 我尝试使用app extensions 但我初始化的一些扩展不在字典中 from flask import current app current app extensions get
  • SQL Server XQuery 返回错误

    我正在 SQL Server 2012 中对 XML 数据类型列执行查询 数据示例如下

随机推荐