【问题标题】:Why does beautiful soup not properly parse element named "area"?为什么美丽的汤不能正确解析名为“区域”的元素?
【发布时间】:2018-05-07 12:17:40
【问题描述】:

我正在编写一个使用beautiful soup 解析xml 文档的python 脚本。一些文档包含名为“区域”的元素。由于某种原因,我无法终生正确解析这些元素。它们总是以空的<area/> 元素出现。

这是正在发生的事情的一个最小示例:

#!/usr/bin/python3.5
from bs4 import BeautifulSoup

xml = """""
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>

<root>
    <areax>
        foo
    </areax>
    <area>
        bar
    </area>
</root>
"""""
soup = BeautifulSoup (xml, "lxml")

print ("\n#### soup ####\n")
print (soup)

print ("\n#### areax ####\n")
areaxs = soup.find_all ("areax")
for areax in areaxs:
    print (areax)

print ("\n### area ###\n")
areas = soup.find_all ("area")
for area in areas:
    print (area)

输出:

#### soup ####

<html><body><p>""
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>
<root>
<areax>
        foo
    </areax>
<area/>
        bar

</root>
</p></body></html>

#### areax ####

<areax>
        foo
    </areax>

### area ###

<area/>

元素名称“区域”是否以任何方式受到保护,还是我解析它的方式有其他问题?

【问题讨论】:

    标签: python xml parsing beautifulsoup


    【解决方案1】:

    您的文档被解析为 HTML,而 area 元素是一个空的 HTML 元素(不能有任何子元素)。

    要将其解析为 XML,请使用 BeautifulSoup(xml, "xml") (docs):

    默认情况下,Beautiful Soup 将文档解析为 HTML。要将文档解析为 XML,请将“xml”作为第二个参数传递给 BeautifulSoup 构造函数:

    soup = BeautifulSoup(markup, "xml")
    

    您需要安装 lxml。


    另一个问题是你的xml 字符串周围有太多引​​号,所以它实际上以"" 开头(尝试打印它)。三个引号 (""") 就足够了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多