1package main 2 3import ( 4 "fmt" 5 6 "github.com/antchfx/xquery/html" 7 "golang.org/x/net/html" 8) 9 10func main() { 11 q := "golang" 12 u := "http://www.bing.com/search?q=" + q 13 doc, err := htmlquery.LoadURL(u) 14 if err != nil { 15 panic(err) 16 } 17 type entry struct { 18 id int 19 title string 20 url string 21 desc string 22 } 23 24 var entries []entry 25 htmlquery.FindEach(doc, "//ol[@id='b_results']/li[@class='b_algo']", func(i int, node *html.Node) { 26 item := entry{} 27 item.id = i 28 h2 := htmlquery.FindOne(node, "//h2") 29 item.title = htmlquery.InnerText(h2) 30 item.url = htmlquery.SelectAttr(htmlquery.FindOne(h2, "a"), "href") 31 if n := htmlquery.FindOne(node, "//div[@class='b_caption']/p"); n != nil { 32 item.desc = htmlquery.InnerText(n) 33 } 34 entries = append(entries, item) 35 }) 36 count := htmlquery.InnerText(htmlquery.FindOne(doc, "//span[@class='sb_count']")) 37 fmt.Println(fmt.Sprintf("%s by %s", count, q)) 38 for _, item := range entries { 39 fmt.Println(fmt.Sprintf("%d title: %s", item.id, item.title)) 40 fmt.Println(fmt.Sprintf("url: %s", item.url)) 41 fmt.Println(fmt.Sprintf("desc: %s", item.desc)) 42 fmt.Println("=====================") 43 } 44} 45