gpt4 book ai didi

python - Xpath提取当前节点内容包括所有子节点

转载 作者:行者123 更新时间:2023-12-01 04:44:02 27 4
gpt4 key购买 nike

我在提取当前节点内容(包括所有子节点)时遇到问题。

就像下面的代码,我想获取字符串 abcdefg<b>b1b2b3</b>在预标记中。

但我无法使用“child::*”来获取它。如果我使用“/text()”,我会丢失b标签格式信息。请帮帮我。

# -*- coding: utf-8 -*-
from lxml import html
import lxml.etree as le

input = "<pre>abcdefg<b>b1b2b3</b></pre>"
input_xpath = "//pre/child::*"
tree = html.fromstring(input)
result = tree.xpath(input_xpath)
result1 = [le.tostring(item) for item in result]
result2 = ''.join(result1)
print result2

output: <b>b1b2b3</b>

最佳答案

要获取 XML 节点的内容标记(有时称为 "innerXML" ),您可以通过选择节点(而不是选择子节点或文本内容)开始:

from lxml import html
import lxml.etree as le

input = "<pre>abcdefg<b>b1b2b3</b></pre>"
tree = html.fromstring(input)
node = tree.xpath("//pre")[0]

然后将文本内容与所有子节点标记组合起来:

result = node.text + ''.join(le.tostring(e) for e in node)
print result

输出:

abcdefg<b>b1b2b3</b>

关于python - Xpath提取当前节点内容包括所有子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29887576/

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