【问题标题】:Removing img tag in lxml删除 lxml 中的 img 标签
【发布时间】:2014-08-31 05:57:19
【问题描述】:

我有这个代码:

from lxml.html import fromstring, tostring

html = "<p><img src='some_pic.jpg' />Here is some text</p>"

doc = fromstring(html)
img = doc.find('.//img')
doc.remove(img)

print tostring(doc)

输出为:&lt;p&gt;&lt;/p&gt;

为什么删除 img 标签也会删除它后面的文本?也就是说,为什么没有打印出结果:&lt;p&gt;Here is some text&lt;/p&gt; 我怎样才能删除该标签而不删除文本?请注意,即使我在 img 上包含显式结束标记,我也会得到相同的结果,即:

html = "<p><img src='some_pic.jpg'></img>Here is some text</p>"

【问题讨论】:

    标签: python html html-parsing lxml lxml.html


    【解决方案1】:

    Here is some text 文本是 img 标记的 tail - 它是元素的一部分,并且正在与元素一起被删除。

    要保留tail - 将其分配给img 父母的文本:

    from lxml.html import fromstring, tostring
    
    html = "<p><img src='some_pic.jpg' />Here is some text</p>"
    
    doc = fromstring(html)
    img = doc.find('.//img')
    parent = img.getparent()
    parent.text = img.tail
    doc.remove(img)
    
    print tostring(doc)
    

    打印:

    <p>Here is some text</p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多