我正在尝试在 Python 3.6.2、IPython 6.1.0、Windows 10 上使用 Beautiful Soup 读取 xml 文档,但我无法获得正确的编码。
这是我的测试 xml,以 UTF8 编码保存为文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<info name="愛よ">ÜÜÜÜÜÜÜ</info>
<items>
<item thing="ÖöÖö">"23Äßßß"</item>
</items>
</root>
首先使用 ElementTree 检查 XML:
import xml.etree.ElementTree as ET
def printXML(xml,indent=''):
print(indent+str(xml.tag)+': '+(xml.text if xml.text is not None else '').replace('\n',''))
if len(xml.attrib) > 0:
for k,v in xml.attrib.items():
print(indent+'\t'+k+' - '+v)
if xml.getchildren():
for child in xml.getchildren():
printXML(child,indent+'\t')
xml0 = ET.parse("test.xml").getroot()
printXML(xml0)
输出是正确的:
root:
info: ÜÜÜÜÜÜÜ
name - 愛よ
items:
item: "23Äßßß"
thing - ÖöÖö
现在用 Beautiful Soup 读取同一个文件并漂亮地打印它:
import bs4
with open("test.xml") as ff:
xml = bs4.BeautifulSoup(ff,"html5lib")
print(xml.prettify())
输出:
<!--?xml version="1.0" encoding="UTF-8"?-->
<html>
<head>
</head>
<body>
<root>
<info name="愛よ">
ÜÜÜÜÜÜÜ
</info>
<items>
<item thing="ÖöÖö">
"23Äßßß"
</item>
</items>
</root>
</body>
</html>
这是错误的。使用指定的显式编码进行调用 bs4.BeautifulSoup(ff,"html5lib",from_encoding="UTF-8") 不会改变结果。
做
print(xml.original_encoding)
输出
None
So Beautiful Soup 显然无法检测到原始编码,即使文件以 UTF8 编码(根据 Notepad++)并且 header 信息也显示为 UTF-8,而且我确实有 chardet安装as the doc recommends .
我在这里犯错了吗?可能是什么原因造成的?
编辑: 当我在没有 html5lib 的情况下调用代码时,我收到此警告:
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib").
This usually isn't a problem, but if you run this code on another system, or in a different virtual environment,
it may use a different parser and behave differently.
The code that caused this warning is on line 241 of the file C:\Users\My.Name\AppData\Local\Continuum\Anaconda2\envs\Python3\lib\site-packages\spyder\utils\ipython\start_kernel.py.
To get rid of this warning, change code that looks like this:
BeautifulSoup(YOUR_MARKUP})
to this:
BeautifulSoup(YOUR_MARKUP, "html5lib")
markup_type=markup_type))
编辑 2:
根据评论中的建议,我尝试了 bs4.BeautifulSoup(ff,"html.parser"),但问题仍然存在。
然后我安装了 lxml 并尝试了 bs4.BeautifulSoup(ff,"lxml-xml"),仍然是相同的输出。
同样让我感到奇怪的是,即使指定像 bs4.BeautifulSoup(ff,"lxml-xml",from_encoding='UTF-8') 这样的编码, 的值xml.original_encoding 是 None 与 written in the doc 相反.
编辑 3:
我将我的 xml 内容放入一个字符串中
xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><info name=\"愛よ\">ÜÜÜÜÜÜÜ</info><items><item thing=\"ÖöÖö\">\"23Äßßß\"</item></items></root>"
并使用了 bs4.BeautifulSoup(xmlstring,"lxml-xml"),现在我得到了正确的输出:
<?xml version="1.0" encoding="utf-8"?>
<root>
<info name="愛よ">
ÜÜÜÜÜÜÜ
</info>
<items>
<item thing="ÖöÖö">
"23Äßßß"
</item>
</items>
</root>
看来文件毕竟有问题。
请您参考如下方法:
发现错误,打开文件时必须指定编码:
with open("test.xml",encoding='UTF-8') as ff:
xml = bs4.BeautifulSoup(ff,"html5lib")
因为我在 Python 3 上,所以我认为 encoding 的值默认是 UTF-8,但事实证明它是系统相关的,在我的系统上它是cp1252。
