如何从lxml text\u content()中排除特定标记锚定的文本

2024-06-09 01:46:03 发布

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

我知道有类似的问题,但由于他们没有解决这个问题,请容忍我为什么要再次讨论这个问题

这是我的字符串:

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 

除了给出错误的输出,这也是不雅的。所以我肯定错过了一些明显的东西,虽然我不知道是什么


Tags: tobryougotargetnotneedthis
1条回答
网友
1楼 · 发布于 2024-06-09 01:46:03

我觉得你把事情弄得太复杂了。无需创建tree_struct对象并使用getpath()。这里有一个建议:

from lxml import html

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 = html.fromstring(normal)

for e in target.iter():
    if not e.tag == "a":
        # Print text content if not only whitespace 
        if e.text and e.text.strip():
            print(e.text.strip())
        # Print tail content if not only whitespace
        if e.tail and e.tail.strip():
            print(e.tail.strip())

输出:

I need this one
Forget me not
even when
you go to sleep
Foremost on your mind

相关问题 更多 >