如何通过lxml解析从htmlfile打印出所有的文本信息?

2024-09-30 02:25:20 发布

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

我有一个这样的html文件:

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

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

我需要为每个p标记获取以下输出:

Definition, sometext, othertext, someothertext.

Definition2, sometext, othertext, someothertext, blabla, bubu.

我尝试用以下代码实现它:

tree = etree.parse(filename)
places = []
for dfn in tree.getiterator('dfn'):
   def_text = dfn.text
   def_tail = dfn.tail
   for sibling in dfn.itersiblings():   
            sib_text = sibling.text
            sib_tail = sibling.tail
            if def_text not in places:
                places.append(def_text)
                if def_tail == None or sib_text == None or sib_tail == None:
                  continue
                else:
                  places.append(def_tail), places.append(sib_text), places.append(sib_tail) 
return places

这给我的输出是正确的一半。例如,它只是跳过此窗体的条目:

<p><dfn>Cityname</dfn>, text 2349 </p> 

或者我从I-tags和它们的部分标签中获取文本。。。 我想问题是关于迭代的,但我真的找不到错误。。。。你知道吗

有什么有效的方法来实现我的目标吗?你知道吗

另外,我还尝试了一些树.xpath('//p/text()'),但它太笼统了,在我的例子中,我需要提取dfn的同级相对于dfn本身的文本:如果dfn是好的(我有更多的代码来定义dfn是否是好的),那么打印出dfn和p标记中随它而来的所有文本。你知道吗


Tags: textin标记文本defhtmltailplaces
2条回答

谢谢你的提示,我有这个给我我需要的:

for p in tree.xpath("//p"):
  dfn = p.xpath('./dfn/text()')
  after_dfn = p.xpath("./dfn/following::text()")
  if dfn!=None:
    print dfn
  if after_dfn !=None:    
    for x in after_dfn:
        print x

唯一的问题是-它导致了一个无限循环,我如何才能摆脱它?你知道吗

我会尝试以下方法:

for p in tree.xpath("//p"):  # This gets all the p elements
    dfn = p.xpath('./dfn')[0]  # may want to check this exists first
    after_dfn = p.xpath("./dfn/following-sibling::node()")
    for x in after_dfn:
        pass  # do whatever you need to do with the stuff after dfn

相关问题 更多 >

    热门问题