【问题标题】:Unexpectedly renaming field in file意外重命名文件中的字段
【发布时间】:2021-02-15 18:09:08
【问题描述】:

我正在使用 Python BS4/lxml 来解析 xml 格式的 RSS 提要(特别是 https://itch.io/games/on-sale.xml)。我发现在从请求接收页面数据和 BS4 从文本中读取它的过渡中,链接字段的名称正在更改。具体来说,res.text 包含...</saleends><link>https://foo.itch.io/bar</link><description>...,但将其读入BS4/lxml 并打印出...</saleends><link/>https://foo.itch.io/bar<description>...,BS4 无法正确解析。我的代码在here,第 237 行可用。

我可以提供项目的精简版本,无需登录和日志记录,以便于测试。

使用简化代码编辑:

import requests
from bs4 import BeautifulSoup
res = requests.get("https://itch.io/feed/sales.xml")
soup = BeautifulSoup(res.text, 'lxml')
print(soup.item.link)

预期行为:打印“https://itch.io/s/12345/foobar”(无论 RSS 中的最新链接是什么) 实际行为:打印“

【问题讨论】:

  • 会这样变化吗?虽然它改变了,对你来说很重要吗?你到底想从 xml 中解析什么?
  • 是的,即使我不明白为什么会这样,它也会发生变化。结果,据我所知,链接的主体是不可寻址的,soup.link 返回字符串“”,而不是我试图抓取的实际链接。

标签: python beautifulsoup python-requests rss lxml


【解决方案1】:

lxml 是 lxml 的 HTML 解析器,lxml-xmlxml 是 lxml 的 XML 解析器。 (请参阅指向this 文档的this 答案)

因此,您应该使用lxml-xmlxml 解析器,而不是使用lxml 解析器。

import requests
from bs4 import BeautifulSoup
res = requests.get("https://itch.io/feed/sales.xml")
soup = BeautifulSoup(res.text, 'lxml-xml')
print(soup.item.link.text)

输出: https://itch.io/s/38593/halloween-event-sale

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多