【问题标题】:How to get Python bs4 to work properly on XML?如何让 Python bs4 在 XML 上正常工作?
【发布时间】:2016-07-08 17:43:07
【问题描述】:

我正在尝试使用 Python 和 BeautifulSoup 4 (bs4) 将 Inkscape SVG 转换为类似 XML 的格式,以供某些专有软件使用。我似乎无法让 bs4 正确解析一个最小的例子。我需要解析器尊重自闭合标签,处理 unicode,而不是添加 html 内容。我认为用 selfClosingTags 指定'lxml'解析器应该这样做,但不!看看吧。

#!/usr/bin/python
from __future__ import print_function
from bs4 import BeautifulSoup

print('\nbs4 mangled XML:')
print(BeautifulSoup('<x><c name="b1"><d value="a"/></c></x>',
    features = "lxml", 
    selfClosingTags = ('d')).prettify())

print('''\nExpected output:
<x>
 <c name="b1">
  <d value="a"/>
 </c>
</x>''')

这会打印出来

bs4 mangled XML:
/usr/local/lib/python2.7/dist-packages/beautifulsoup4-4.4.1-py2.7.egg/bs4/__init__.py:112: UserWarning: BS4 does not respect the selfClosingTags argument to the BeautifulSoup constructor. The tree builder is responsible for understanding self-closing tags.
<html>
 <body>
  <x>
   <c name="b1">
    <d value="a">
    </d>
   </c>
  </x>
 </body>
</html>

Expected output:
<x>
 <c name="b1">
  <d value="a"/>
 </c>
</x>

我查看了相关的 StackOverflow 问题,但没有找到解决方案。

This question 处理 html 样板,但仅用于解析 html 的子部分,而不用于解析 xml。

This question 与让 beautifulsoup 4 尊重自闭合标签有关,并且没有可接受的答案。

This question 似乎表明传递 selfClosingTags 参数应该会有所帮助,但正如您所看到的,现在这会生成警告 BS4 does not respect the selfClosingTags argument,并且自关闭标签被破坏。

This question 建议使用“xml”(而不是“lxml”)会导致空标签自动关闭。这可能适用于我的目的,但将“xml”解析器应用于我的实际数据失败,因为文件包含 unicode,而“xml”解析器不支持。

“xml”和“lxml”有区别吗,标准中“xml”不能支持unicode,“lxml”不能包含自闭标签?也许我只是想做一些被禁止的事情?

【问题讨论】:

  • “因为文件包含 unicode,“xml”解析器不支持”→ 不,XML 解析器根据定义支持 Unicode。您应该发布一个关于如何打开和写入文件的最小示例。
  • 为什么不使用 lxml 本身?

标签: python xml unicode beautifulsoup bs4


【解决方案1】:

如果您希望将结果输出为xml,然后将其解析为。您的xml 数据可以包含 unicode,但是,您需要声明编码:

#!/usr/bin/env python
# -*- encoding: utf8 -*-

The SelfClosingTags is no longer recognized。相反,美丽 Soup 认为任何空标签都是空元素标签。如果你添加一个 child 到一个空元素标签,它不再是一个空元素标签。

改变你的函数看起来像这样应该可以工作(除了编码):

print(BeautifulSoup('<x><c name="b1"><d value="a®"/></c></x>',
    features = "xml").prettify())

结果:

<?xml version="1.0" encoding="utf-8"?>
<x>
 <c name="b1">
  <d value="aÂŽ"/>
 </c>
</x>

【讨论】:

  • 您的编码声明声明了源文件的编码。这与问题无关。
  • @roeland:这是相关的,因为没有它,XML 中的任何 unicode 字符都会导致语法错误。 Non-ASCII character: but no encoding declared; python.org/dev/peps/pep-0263
  • 但是 OP 正在从 SVG 文件加载 XML。
  • Stackoverflow 没有办法包含带有问题的文件,所以我无法制作 SVG 示例,这就是我们有纯 Python 示例的原因。
  • @MRule:https://gist.github.com/ 非常适用于更详细的内容——因此您不仅限于在此处发布最小示例。然后你可以在你的问题中提供一个链接......
猜你喜欢
  • 2020-11-07
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2020-08-27
  • 2018-06-11
  • 2016-08-27
  • 1970-01-01
相关资源
最近更新 更多