在lxml中移除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')
doc.remove(img)
print tostring(doc)
输出结果是:<p></p>
为什么去掉标签后,后面的文字也没了?换句话说,为什么结果不是:
<p>这里有一些文字</p>
?我怎么才能只去掉那个标签,而不去掉文字呢?注意,即使我在标签后面加上了明确的闭合标签,结果还是一样的:
html = "<p><img src='some_pic.jpg'></img>Here is some text</p>"
1 个回答
2
这里有一些文本
这个文本是 img
标签的 尾部
- 它是元素的一部分,并且会随着元素一起被移除。
为了保留 尾部
- 你可以把它赋值给 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>