首页 > 编程语言 > 详细

go语言使用xpath

时间:2019-04-29 01:22:15      阅读:434      评论:0      收藏:0      [点我收藏+]

1.导包

 gopm get -g -v github.com/lestrrat-go/libxml2

2.使用示例

func ExampleHTML() {
  res, err := http.Get("http://golang.org")
  if err != nil {
    panic("failed to get golang.org: " + err.Error())
  }

  doc, err := libxml2.ParseHTMLReader(res.Body)
  if err != nil {
    panic("failed to parse HTML: " + err.Error())
  }
  defer doc.Free()

  doc.Walk(func(n types.Node) error {
    log.Printf(n.NodeName())
    return nil
  })

  nodes := xpath.NodeList(doc.Find(`//div[@id="menu"]/a`))
  for i := 0; i < len(nodes); i++ {
    log.Printf("Found node: %s", nodes[i].NodeName())
  }
}

//bytes[]转io.Reader()的例子

package parser

import (
    "bytes"
    "fmt"
    "github.com/lestrrat-go/libxml2"
    "goproject/crawler/Fetcher"
    "testing"
)

func TestParseCityList(t *testing.T) {
    contents, err := Fetcher.Fetch("http://www.zhenai.com/zhenghun")
    if err != nil {
        panic(err)
    }   
    //bytes[]转io.Reader()
    doc, err := libxml2.ParseHTMLReader(bytes.NewReader(contents))
    defer doc.Free()
    nodes, err := doc.Find("//dl[@class='city-list clearfix']/dd/a")
    fmt.Println(nodes.NodeList()[0].TextContent(), err)
}

go语言使用xpath

原文:https://www.cnblogs.com/c-x-a/p/10787962.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!