Golang通過pup實現HTML解析

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

上一周給我的網站加了一個搜尋功能,能自動抓取我的部落格和別人的CSDN部落格。通過RSS抓取。這樣資料格式規範,容易解析。問題是資訊較少。後來發現在HTML原始碼裡面,會有為了方便搜尋引擎索引的meta欄位,能指出作者和詳情。以我的部落格《Golang實現HTTP發送gzip請求》為例。裡面的meta資訊如下:

<meta charset="utf-8"><meta name="description" content="beego的httplib不支援發送gzip請求,自己研究了一下。"><meta name="author" content="Bryce"><meta name="google-translate-customization" content="a4136e955b3e09f2-45a74b56dc13e741-gf616ffda6e6360e0-11"><meta name="viewport" content="width=device-width, initial-scale=1.0">

查了查,一般大家通過xpath進行解析。有一個現成的包https://github.com/go-xmlpath/xmlpath,按照說明做了一下,不行。看了一下源碼,這個包內部是通過encoding/xml實現的,如果HTML的代碼有問題,標籤不是嚴格按照規範編寫的,就會有解析問題。同理,如果把HTML當作XHTML處理,也是不行的。

後來發現一個神奇的工具https://github.com/EricChiang/pup,通過命令go get github.com/ericchiang/pup安裝。它可以通過管道調用:

curl -s http://blog.cyeam.com | pup 'div div div div h2 a' 

直接抓取作者和簡介可以用如下命令:

curl -s http://blog.cyeam.com/golang/2014/11/29/golang_gzip/ | pup 'head meta[name="author"] attr{content}'curl -s http://blog.cyeam.com/golang/2014/11/29/golang_gzip/ | pup 'head meta[name="description"] attr{content}' 

這個包能完美解決我的問題,進去看了一下源碼,發現包名是main,再一個是因為它用來解析HTML不是那麼方便,想了想,我囧的還是用cmd的方式通過管道執行。

req := httplib.Get("http://blog.cyeam.com/golang/2014/11/29/golang_gzip/")res, err := req.Bytes()if err != nil {panic(err)}cmd := exec.Command("pup", `head meta`)stdin, err := cmd.StdinPipe()if err != nil {panic(err)}// defer stdin.Close()var output bytes.Buffercmd.Stdout = &outputif err = cmd.Start(); err != nil { //Use start, not runfmt.Println("An error occured: ", err) //replace with logger, or anything you want}stdin.Write(res)stdin.Close()if err := cmd.Wait(); err != nil {panic(err)}fmt.Println(string(output.Bytes())) //for debug

通過shell命令列管道是通過|實現,而通過Golang代碼,需要通過exec包提供的Stdin實現。把內容寫入標準輸入資料流,就相當於管道輸入了。寫完了要關閉輸入資料流stdin.Close(),如果不關閉,輸入資料流不會被寫入。。。

本文所涉及到的完整源碼請參考。

######參考文獻+ 【1】Package exec - The Go Programming Language+ 【2】golang講解(go語言)標準庫分析之os/exec - widuu

原文連結:Golang通過pup實現HTML解析,轉載請註明來源!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.