用Tcl解析(Parse)HTML

@ 2009-07-19 15:34:08
标签:

    # 2008/10/27 00:29 @ root

    如何用 Tcl 从HTML文档中抽取感兴趣的信息呢。这涉及到文档的解析。通常有两种方式 SAX 和 DOM。

    SAX 属于边parse边处理的方式。DOM 则先把文档变成特定的数据结构后,再来处理。

    这方面的介绍并不是很多。这里介绍一下最近项目中使用的方法。

    namespace eval nyno {}
    
    proc nyno::puts {{txt "\x01"} {el "\n"}} {
        variable text_buf
        if {$txt == "\x01"} { set text_buf "" }
        set text_buf "$text_buf$txt$el"
    }
    
    proc nyno::parse_snps_job {tag slash param text} {
        variable in_job
    
        switch "$slash$tag" {
            "docroot" {set in_job 0}
            "h1"  {
                set in_job 1
                nyno::puts "===== $text ====="
            }
            "hr"  {set in_job 0}
        }
        if {$in_job == 0} return
    
        switch "$slash$tag" {
            "h2"    { nyno::puts "\n==== $text ====\n"}
            "label" { nyno::puts [::textutil::trim  $text {[ \t\r\n]+}] "" }
            "span" {
                if [regexp {class="field readOnly"} $param] { nyno::puts " $text" }
            }
            "p" {  nyno::puts "$text"  }
        }
    }
    # Do the parse below
    nyno::puts
    ::htmlparse::parse -cmd nyno::parse_snps_job -vroot "docroot" $html
    puts [::htmlparse::mapEscapes $nyno::text_buf] 
    

    http://tcllib.sourceforge.net/doc/htmlparse.html|htmlparsehttp://tcllib.sourceforge.net/|TclLib 的一部分。

    上面的例子用的是 SAX 的方式。关键部分是回调函数的编写。

    htmlparse 也提供类似 DOM 的处理方式 ::htmlparse::2tree。

    标签:

      分享到:
      comments powered by Disqus

      29/31ms