问题
I've met a problem while extracting current node content including all child node.
Just like the following code, I want to get string
abcdefg<b>b1b2b3</b>
in pre tag.
But I could not use "child::*" to get it. If I use "/text()", I lost b tag format information. Please help me out.
# -*- 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>
回答1:
To get XML node's content markup (sometimes referred to as "innerXML") , you can start by selecting the node (instead of selecting the child or the text content) :
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]
then combine the text content with all child nodes markup :
result = node.text + ''.join(le.tostring(e) for e in node)
print result
Output :
abcdefg<b>b1b2b3</b>
回答2:
try replacing your xpath with the following
In [0]: input = "<pre>abcdefg<b>b1b2b3</b></pre>"
In [1]: input_xpath = "//pre//text()"
In [2]: tree = html.fromstring(input)
In [3]: result = tree.xpath(input_xpath)
In [4]: result
Out[5]: ['abcdefg', 'b1b2b3']
来源:https://stackoverflow.com/questions/29887576/xpath-extract-current-node-content-including-all-child-node