BeautifulSoup 不会使用 utf-8 以外的其他编码解析 xml

Chr*_*las 5 xml encoding beautifulsoup python-3.x

我可以读取以 .xml 开头的所有 xmls 文件,<?xml version="1.0" encoding="utf-8"?>但无法读取以.xml 开头的文件<?xml version="1.0" encoding="ISO-8859-1"?>

具体来说,我有两个文件:

xml_iso.xml :

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
</note>
Run Code Online (Sandbox Code Playgroud)

xml-utf.xml :

<?xml version="1.0" encoding="utf-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
</note>
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我可以找到note文件的 ,utf-8但我无法在其他编码的文件中找到它。我该如何解决?

示例代码:

import unittest

from bs4 import BeautifulSoup as Soup

class TestEncoding(unittest.TestCase):
    def test_iso(self):
        with open('tests/xml-iso.xml', 'r') as f_in:
            xml_soup = Soup(f_in.read(), 'xml')
        print('xml-iso:\n{}'.format(xml_soup))
        note = xml_soup.find('note')
        self.assertIsNotNone(note)

    def test_utf8(self):
        with open('tests/xml-utf.xml', 'r') as f_in:
            xml_soup = Soup(f_in.read(), 'xml')
        print('xml-utf8:\n{}'.format(xml_soup))
        note = xml_soup.find('note')
        self.assertIsNotNone(note)

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

版本:

  • 蟒蛇 3.5.2

  • beautifulsoup4==4.6.0

Fab*_*ius 5

巧合的是,我偶然发现了另一种解决方法。以二进制方式读取文件('rb'):

with open('tests/xml-iso.xml', 'rb') as f_in:
    xml_soup = Soup(f_in.read(), 'xml')
Run Code Online (Sandbox Code Playgroud)


mr.*_*rre 1

我有完全一样的问题。我的解决方法是不读取 xml 声明:

with open('tests/xml-iso.xml', 'r', encoding='iso-8859-1') as f_in:
    f_in.readline()  # skipping header and letting soup create its own header
    xml_soup = Soup(f_in.read(), 'xml', from_encoding='ISO-8859-1')
Run Code Online (Sandbox Code Playgroud)