加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang使用xpath解析html例子

发布时间:2020-12-16 18:26:25 所属栏目:大数据 来源:网络整理
导读:今天在找golang下的xpath库,使用 libxml2 不错。使用示例: package mainimport ("fmt""log""net/http""github.com/lestrrat/go-libxml2")type MyResponse struct {*http.Response}func (response *MyResponse) String() string {return fmt.Sprint(response

今天在找golang下的xpath库,使用libxml2不错。使用示例:

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/lestrrat/go-libxml2"
)

type MyResponse struct {
	*http.Response
}

func (response *MyResponse) String() string {
	return fmt.Sprint(response.Response)
}

func request(method string,url string) *MyResponse {
	client := http.Client{}
	request,err := http.NewRequest(method,url,nil)
	request.Header.Set("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0")
	response,err := client.Do(request)

	if err != nil {
		log.Fatal(err)
	}

	my_response := &MyResponse{response}
	return my_response
}

func main() {
	response := request("GET","http://www.duoshoubang.cn")
	if doc,err := libxml2.ParseHTMLReader(response.Body); err != nil {
		log.Fatal(err)

	} else {
		defer doc.Free()
		nodes,err := doc.Find("//div[@class='row download']//img/@src")
		fmt.Println(nodes.NodeList()[0].TextContent(),err)
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读