在Python中,如何去掉HTML片段中的“root”标签?
假设我有一段这样的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()
但这样只给我返回了“Hello”,我想这也没什么问题。有没有更好的办法呢?
3 个回答
0
对于这么简单的任务,你可以使用正则表达式,比如 r'<(.*?)>(.*)</\1>'
,这样就能从中提取出第二部分内容(在perl中叫做\2)。
你还应该加上像 ms
这样的标志,以确保它在多行文本中能正常工作。
1
你可以使用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。
6
在使用lxml(或者ElementTree)时,这个情况有点奇怪。你需要这样做:
def inner_html(el):
return (el.text or '') + ''.join(tostring(child) for child in el)
需要注意的是,lxml(和ElementTree)没有特别的方式来表示一个文档,文档必须以一个单独的元素为根。不过,如果那个<div>
不是根元素的话,.drop_tag()
就能像你想的那样工作。