lxml:如何只迭代第一/第二兄弟?

2024-10-05 14:22:07 发布

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

我有一个这种html文档:

<html>
 <head></head>
 <body>
   <p>
     <dfn>text</dfn>sometext
     **<i>othertext</i>**
     <i>...</i>
     <i>...</i></p>
   <p>
     <dfn>text</dfn>sometext
     **<i>othertext</i>**
     <i>...</i>
     <i>...</i></p>
  </body>
 </html>

我需要对其进行解析,以便能够从每个第一个I-tag中获取文本,以及关于dfn的文本(我将最终提取dfn文本) 目前我的代码是:

^{pr2}$

这会遍历每个i-tag,有时会给我错误的输出。我如何将迭代限制在dfn的第一个同级?在


Tags: 代码text文档文本htmltag错误body
1条回答
网友
1楼 · 发布于 2024-10-05 14:22:07

找到匹配项时,请退出itersiblings()循环:

for dfn in tree.iter('dfn'):
    bu = dfn.text
    for sibling in dfn.itersiblings():   
        su = sibling.text
        if su != None and bu != None and re.findall(..,su):
            places.append(bu)
            break

break语句提前结束for sibling循环,不再处理其他同级。相反,外部的for dfn循环继续下一个dfn元素。在

相关问题 更多 >