[英]In Python, how do I remove the “root” tag in an HTML snippet?
假设我有一个这样的HTML代码段:
<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()
但这只会给我“你好”,我认为这很有意义。 有更好的想法吗?
在lxml(或ElementTree)中这有点奇怪。 您必须执行以下操作:
def inner_html(el):
return (el.text or '') + ''.join(tostring(child) for child in el)
请注意,lxml(和ElementTree)除了以单个元素为根以外,没有其他表示文档的特殊方法,但是如果<div>
不是根元素, .drop_tag()
会像您希望的那样工作。
您可以使用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 。
对于这样一个简单的任务,您可以使用regexp之类的r'<(.*?)>(.*)</\\1>'
并从中获取匹配项2(在perl中为\\ 2)
您还应该放置ms
标记,以确保正确的多行工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.