使用streamhtmlpars的示例

2024-09-28 12:16:24 发布

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

有谁能给我一个例子,说明如何使用http://code.google.com/p/streamhtmlparser从html文档中解析出所有的A标记href?(C++代码或Python代码都可以,但我更喜欢使用Python绑定的例子)

我可以看到它在python测试中是如何工作的,但是他们期望html中已经有了特殊的标记,在那里它检查状态值。我不知道在向解析器提供纯html时,如何在状态更改期间获得正确的回调。在

我可以用下面的代码获得一些我想要的信息,但是我需要一次给它提供html块,而不仅仅是字符,我需要知道什么时候用一个标记、属性等完成,而不仅仅是在一个标记、属性或值中。在

import py_streamhtmlparser
parser = py_streamhtmlparser.HtmlParser()
html = """<html><body><a href='http://google.com'>link</a></body></html>"""
for index, character in enumerate(html):
   parser.Parse(character)
   print index, character, parser.Tag(), parser.Attribute(), parser.Value(), parser.ValueIndex()

您可以看到此代码的运行示例here


Tags: 代码py标记comhttpparserindex属性
1条回答
网友
1楼 · 发布于 2024-09-28 12:16:24
import py_streamhtmlparser
parser = py_streamhtmlparser.HtmlParser()
html = """<html><body><a href='http://google.com' id=100>
        link</a><p><a href=heise.de/></body></html>"""
cur_attr = cur_value = None
for index, character in enumerate(html):
   parser.Parse(character)
   if parser.State() == py_streamhtmlparser.HTML_STATE_VALUE:
      # we are in an attribute value. Record what we got so far
      cur_tag = parser.Tag()
      cur_attr = parser.Attribute()
      cur_value = parser.Value()
      continue
   if cur_value:
      # we are not in the value anymore, but have seen one just before
      print "%r %r %r" % (cur_tag, cur_attr, cur_value)
      cur_value = None

给予

^{pr2}$

如果只需要href属性,请在打印时检查cur峎u attr。在

Edit:Python绑定当前不支持任何类型的事件回调。因此,唯一可用的输出是处理相应输入时的状态。为了改变这种情况,可以使用回调函数来扩充htmlparser.c:exit_attr(等等)。然而,这并不是streamhtmlparser的目的——它是一个模板引擎,在源代码中有标记,然后逐个字符地处理输入。在

相关问题 更多 >

    热门问题