返回带有标记/标记的HTMl Xpath

2024-10-01 02:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

输入Html

<section id="article">
  <p>Hey This is XXX</p>
</section>

我使用lxmlxpath提取数据

xpath_paragraph = '//section[@id="article"]/p//text()'
items = mydoc.xpath(xpath_paragraph)

我得到的结果是:

Hey This is XXX

预期结果:

<p>Hey This is XXX</p>

结果是可以理解的,我正在提取文本,我也尝试了node()。它也不起作用。我需要用标签提取数据。你知道吗


Tags: 数据textidishtmlarticlesectionitems
2条回答

这应该对你有用

import xml.etree.ElementTree as ET

data='''
<section id="article">
 <p>Hey This is XXX</p>
 </section>'''

root = ET.fromstring(data)
for value in root.iter('section'):
    rank=value.find('p').text


#this is to initialize child  
for child in root:
    pass
    #print child.tag,child.attrib

print '<'+child.tag+'>'+rank+'</'+child.tag+'>'

输出

<p>Hey This is XXX</p>

如果要显式选择文本节点('//section[@id=“article”]/p//text()'),请尝试以下表达式

xpath_paragraph = '//section[@id="article"]/p'

应该选择p元素

相关问题 更多 >