【问题标题】:How to get BeautifulSoup 4 to respect a self-closing tag?如何让 BeautifulSoup 4 尊重自闭标签?
【发布时间】:2013-02-04 08:54:03
【问题描述】:

这道题是针对BeautifulSoup4的,这使得它与之前的问题有所不同:

Why is BeautifulSoup modifying my self-closing elements?

selfClosingTags in BeautifulSoup

既然BeautifulStoneSoup 已经消失(以前的xml 解析器),我怎样才能让bs4 尊重一个新的自闭合标签?例如:

import bs4   
S = '''<foo> <bar a="3"/> </foo>'''
soup = bs4.BeautifulSoup(S, selfClosingTags=['bar'])

print soup.prettify()

不会自动关闭bar 标签,但会给出提示。 bs4 所指的这个树生成器是什么以及如何自我关闭标签?

/usr/local/lib/python2.7/dist-packages/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.
  "BS4 does not respect the selfClosingTags argument to the "
<html>
 <body>
  <foo>
   <bar a="3">
   </bar>
  </foo>
 </body>
</html>

【问题讨论】:

    标签: python xml xml-parsing beautifulsoup


    【解决方案1】:

    To parse XML you pass in “xml” as the second argument to the BeautifulSoup constructor.

    soup = bs4.BeautifulSoup(S, 'xml')
    

    You’ll need to have lxml installed.

    您不再需要传递selfClosingTags

    In [1]: import bs4
    In [2]: S = '''<foo> <bar a="3"/> </foo>'''
    In [3]: soup = bs4.BeautifulSoup(S, 'xml')
    In [4]: print soup.prettify()
    <?xml version="1.0" encoding="utf-8"?>
    <foo>
     <bar a="3"/>
    </foo>
    

    【讨论】:

    • 这通过传递selfClosingTags 的列表来工作,但它仍然给出与上面相同的警告。我做错了吗?
    • 没关系,文档回答了这个问题。好像xml模式下的自闭标签是在内容为空的时候自动做的,不应该传一个list。
    • 对。添加了演示。
    • 你知道是否可以使用 BS4 来创建一个自闭合标签(使用new_tag)?
    • @detly,如果为空,它将自动关闭(在 XML 模式下)。
    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多