golang使用xpath解析html例子

前端之家收集整理的这篇文章主要介绍了golang使用xpath解析html例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天在找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)
	}
}
原文链接:https://www.f2er.com/go/189344.html

猜你在找的Go相关文章