1、嘮嘮叨叨
在我之前的文章中講述過如何利用xpath來抓取網頁的內容,不過之前的開發語言我都是使用的Python。如果GoLang也想用Xpath該如何使用呢?下面就來簡單的講一下如何用Golang爬取github.com的一些小內容來做切入點學會這個知識吧。
回顧一下:
2、先看一下效果
比如爬取github.com的這幾個控件的內容
爬取後得到的內容:
3、項目所需包
先安裝項目所需的包,再說其它:
https://github.com/pkg/errors
https://github.com/lestrrat-go/libxml2
4、核心代碼
/**
Author: 沙振宇
CreateTime:2019-12-4
UpdateTime:2019-12-4
Info: “利用 Xpath 讀取 html 內容”
“通過Github來演示Xpath如何使用”
*/
package main
import (
"fmt"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xpath"
"net/http"
"strings"
)
// 去除空格和換行符
func getReplace(str string) string{
// 去除空格
str = strings.Replace(str, " ", "", -1)
// 去除換行符
str = strings.Replace(str, "\n", "", -1)
return str
}
func main() {
urlPath := "https://github.com/"
res, err := http.Get(urlPath)
if err != nil {
panic("failed to get : " + err.Error())
}
doc, err := libxml2.ParseHTMLReader(res.Body)
if err != nil {
panic("failed to parse HTML: " + err.Error())
}
defer doc.Free()
nodes := xpath.NodeList(doc.Find(`//summary[@class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"]/text()`))
fmt.Printf("nodes type: %T,len: %d\n\n", nodes, len(nodes))
for i := 0; i < len(nodes); i++ {
fmt.Printf("nodes type: %T,text: %s\n", nodes[i], getReplace(nodes[i].String()))
}
}
5、Github源碼分享
https://github.com/ShaShiDiZhuanLan/Demo_Xpath_Go
6、其它小知識
6.1、git代碼回滾
再用git上傳代碼導github中,遇到了一個問題,就是我想要刪除一些沒必要的commit記錄。於是我把代碼回滾到之前的記錄,然後commit一下。查看本地庫已經刪除了,但push時發現怎麼也push不上去,後來直接使用強制提交git push -f
才提交成功。
# 注: n代表想往前回滾的次數
git reset --hard HEAD~n
# 強制提交
git push -f -u origin 分支名
6.2、github訪問過慢
github.com訪問有時過慢,於是利用“http://tool.chinaz.com/dns”查詢了DNS鏈接最快的響應IP:
把這個IP配置到hosts中,
windows的話在:“C:\Windows\System32\drivers\etc\hosts”中配置,
linux的話再:“/etc/hosts”中配置
例如上述,把以下配置到hosts末尾即可:
52.74.223.119 github.com