我知道有类似的问题,但由于他们没有解决这个问题,请容忍我为什么要再次讨论这个问题
这是我的字符串:
normal = """
<p>
<b>
<a href='link1'> Forget me </a>
</b> I need this one <br>
<b>
<a href='link2'> Forget me too </a>
</b> Forget me not <i>even when</i> you go to sleep <br>
<b> <a href='link3'> Forget me three </a>
</b> Foremost on your mind <br>
</p>
"""
我从以下几点开始:
target = lxml.html.fromstring(normal)
tree_struct = etree.ElementTree(target)
现在,我基本上需要忽略由<a>
标记锚定的所有内容。但如果我运行这个代码:
for e in target.iter():
item = target.xpath(tree_struct.getpath(e))
if len(item)>0:
print(item[0].text)
我一无所获;另一方面,如果我将print
指令更改为:
print(item[0].text_content())
我得到这个输出:
Forget me
I need this one
Forget me too
Forget me not
even when
you go to sleep
Forget me three
Foremost on your mind
我想要的结果是:
I need this one
Forget me not
even when
you go to sleep
Foremost on your mind
除了给出错误的输出,这也是不雅的。所以我肯定错过了一些明显的东西,虽然我不知道是什么
我觉得你把事情弄得太复杂了。无需创建
tree_struct
对象并使用getpath()
。这里有一个建议:输出:
相关问题 更多 >
编程相关推荐