【问题标题】:In Python, how do I remove the "root" tag in an HTML snippet?在 Python 中,如何删除 HTML 片段中的“根”标签?
【发布时间】:2010-06-09 04:13:54
【问题描述】:

假设我有一个这样的 HTML sn-p:

<div>
  Hello <strong>There</strong>
  <div>I think <em>I am</em> feeing better!</div>
  <div>Don't you?</div>
  Yup!
</div>

删除周围根元素的最佳/最可靠的方法是什么,所以它看起来像这样:

Hello <strong>There</strong>
<div>I think <em>I am</em> feeing better!</div>
<div>Don't you?</div>
Yup!

我尝试过像这样使用 lxml.html:

lxml.html.fromstring(fragment_string).drop_tag()

但这只会给我“你好”,我想这是有道理的。有更好的想法吗?

【问题讨论】:

    标签: python html


    【解决方案1】:

    这在 lxml(或 ElementTree)中有点奇怪。你必须这样做:

    def inner_html(el):
        return (el.text or '') + ''.join(tostring(child) for child in el)
    

    请注意,lxml(和 ElementTree)除了以单个元素为根外,没有特殊的方式来表示文档,但如果 &lt;div&gt; 不是根元素,.drop_tag() 会像您想要的那样工作。

    【讨论】:

    • 效果很好;谢谢!只是为了完成这个: def remove_root(html): parsed = lxml.html.fromstring(html) return (parsed.text or '') + ''.join([lxml.html.tostring(child) for child in parsed] )
    【解决方案2】:

    您可以使用 BeautifulSoup 包。对于这个特定的 html,我会这样:

    import BeautifulSoup
    
    html = """<div>
      Hello <strong>There</strong>
      <div>I think <em>I am</em> feeing better!</div>
      <div>Don't you?</div>
      Yup!
    </div>"""
    
    bs = BeautifulSoup.BeautifulSoup(html)
    
    no_root = '\n'.join(map(unicode, bs.div.contents))
    

    BeautifulSoup 有许多不错的功能,可让您针对许多其他情况调整此示例。完整文档:http://www.crummy.com/software/BeautifulSoup/documentation.html

    【讨论】:

      【解决方案3】:

      对于这样一个简单的任务,您可以使用正则表达式 r'&lt;(.*?)&gt;(.*)&lt;/\1&gt;' 并从中获取匹配#2(perl 术语中的 \2)

      您还应该设置ms 之类的标志以确保正确的多行工作

      【讨论】:

      • 如果你相信它的格式正确,你可以这样做xml.split('&gt;', 1)[1].rsplit('&lt;', 1)[0]
      猜你喜欢
      • 2012-02-01
      • 2014-03-28
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多