Ⅰ. はじめに
タイトルの通り「GoでHTMLの要素をXPathで取得する方法」です。
Ⅱ. やり方
1. パッケージをインストールする
go get github.com/antchfx/htmlquery
2. サンプルプログラムを書く
package main import ( "fmt" "github.com/antchfx/htmlquery" ) func main() { doc, _ := htmlquery.LoadURL("http://example.com") // h1タグのInnerTextを取得する titleElement := htmlquery.FindOne(doc, "/html/body/div/h1") fmt.Println(htmlquery.InnerText(titleElement)) // aタグのhref属性を取得する linkElement := htmlquery.FindOne(doc, "/html/body/div/p[2]/a") fmt.Println(htmlquery.SelectAttr(linkElement, "href")) // pタグを列挙し、InnerTextを表示する for i, x := range htmlquery.Find(doc, "/html/body/div/p") { fmt.Println(i, htmlquery.InnerText(x)) } }
3. 実行結果
Example Domain http://www.iana.org/domains/example 0 This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission. 1 More information...
その他
http://example.com の HTML が変わるとサンプルの意味が無くなるので、
念のため http://example.com のバックアップを残します。
https://gist.github.com/anonymous/e325a74047edab47a2cf6ccdef60af95