在用lxml解析Python时如何防止无限循环?

2024-06-28 20:41:13 发布

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

有这样一个html文件:

<html>
  <head></head>
   <body>
    <p>
      <dfn>A</dfn>sometext / ''
       (<i>othertext</i>)someothertext / ''
       (<i>...</i>)
       (<i>...</i>)
    </p>
    <p>
      <dfn>B</dfn>sometext / ''
      (<i>othertext</i>)someothertext / ''
      <i>blabla</i>
      <i>bubu</i>
    </p>
  </body>
</html>

sometext/''表示dfn标记后面可以有或不能有某些文本,对于i标记也是如此。而且,它们中的i标记和文本并不总是存在的。只有dfn标记中的文本始终存在。你知道吗

我需要从每个p标签中获取所有文本信息:

A, sometext, othertext, someothertext.

B, sometext, othertext, someothertext.

C, sometext, othertext, someothertext.

...

Z, sometext, othertext, someothertext.

下面的代码几乎可以正常工作,只是在给出输出时它会进入无限循环。你知道吗

for p in tree.xpath("//p"):
    dfn = p.xpath('./dfn/text()')
    after_dfn = p.xpath("./dfn/following::text()")
    print '\n'.join(dfn), ''.join(after_dfn)

所以,假设我有ABC的所有字母,我有这样的输出:

> A, sometext, othertext, someothertext.
> 
> B, sometext, othertext, someothertext.
> 
> C, sometext, othertext, someothertext.
> 
> ...
> 
> Z, sometext, othertext, someothertext.
> (2nd unnecessary loop):
> 
> B, sometext, othertext, someothertext.
> 
> C, sometext, othertext, someothertext.
> 
> D, sometext, othertext, someothertext.
> 
> ...
> 
> Z, sometext, othertext, someothertext.
> (3rd unnecessary loop):
> 
> C, sometext, othertext, someothertext.
> 
> D, sometext, othertext, someothertext.
> 
> E, sometext, othertext, someothertext.
> 
> ...
> 
> Z, sometext, othertext, someothertext...etc

奇怪的是从第一个p到最后一个p,然后从第二个p到最后一个p,然后从第三个p到最后一个p,依此类推。。。 从最初107kb的xml文件中,我得到了26mb的巨大恐惧! 拜托,帮我阻止这些循环。你知道吗


Tags: 文件text标记文本htmlbodyxpathhead
1条回答
网友
1楼 · 发布于 2024-06-28 20:41:13

要获取p下面的所有文本,只需执行以下操作:

tree.xpath("//p//text()")

如果需要按p聚合它们,请执行以下操作:

[[y.strip() for y in x.xpath('.//text()') if y.strip()] for x in tree.xpath('//p')]

基于i文本提取p文本:

>>> [y.strip() for y in x.xpath('//i[.="blabla"]/..//text()') if y.strip()]
['B', 'sometext', 'othertext', 'someothertext', 'blabla', 'bubu']

或通过dfn文本:

>>> [y.strip() for y in x.xpath('//dfn[.="B"]/..//text()') if y.strip()]
[['B', 'sometext', 'othertext', 'someothertext', 'blabla', 'bubu']]

相关问题 更多 >