gpt4 book ai didi

Python、lxml 和使用 lxml.html.tostring(el) 删除外部标签

转载 作者:太空狗 更新时间:2023-10-30 01:03:20 28 4
gpt4 key购买 nike

我正在使用下面的代码获取一个部分的所有 html 内容以保存到数据库

el = doc.get_element_by_id('productDescription')
lxml.html.tostring(el)

产品描述有一个标签,看起来像这样:

<div id='productDescription'>

<THE HTML CODE I WANT>

</div>

代码效果很好,给了我所有的 html 代码,但我如何删除外层,即 <div id='productDescription'>和结束标记 </div>

最佳答案

您可以将每个 child 单独转换为字符串:

text = el.text
text += ''.join(map(lxml.html.tostring, el.iterchildren()))

或者以更 hackish 的方式:

el.attrib.clear()
el.tag = '|||'
text = lxml.html.tostring(el)
assert text.startswith('<'+el.tag+'>') and text.endswith('</'+el.tag+'>')
text = text[len('<'+el.tag+'>'):-len('</'+el.tag+'>')]

关于Python、lxml 和使用 lxml.html.tostring(el) 删除外部标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9282398/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com