Python、lxml 和使用 lxml.html.tostring(el) 删除外部标签
我正在使用下面的内容来获取一个部分的所有 html 内容以保存到数据库
el = doc.get_element_by_id('productDescription')
lxml.html.tostring(el)
产品描述有一个如下所示的标签:
<div id='productDescription'>
<THE HTML CODE I WANT>
</div>
代码效果很好,给了我所有的 html 代码,但是如何删除外部层,即
和结束标记
I am using the below to get all of the html content of a section to save to a database
el = doc.get_element_by_id('productDescription')
lxml.html.tostring(el)
The product description has a tag that looks like this:
<div id='productDescription'>
<THE HTML CODE I WANT>
</div>
The code works great , gives me all of the html code but how do I remove the outer layer i.e. the <div id='productDescription'>
and the closing tag </div>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个可以完成您想要的功能的函数。
Here is a function that does what you want.
使用正则表达式。
Use regexp.
您可以将每个子项单独转换为字符串:
或者以更黑客的方式:
You could convert each child to string individually:
Or in even more hackish way:
如果您的
productDescription
div
div 包含混合文本/元素内容,例如您可以使用
xpath('node()')遍历:
if your
productDescription
div
div contains mixed text/elements content, e.g.you can get the content (in string) using
xpath('node()')
traversal: