2 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個(gè)贊
Golang 官方提供了擴(kuò)展包:charset和encoding。
下面的代碼確保 HTML 包可以正確解析文檔:
func detectContentCharset(body io.Reader) string {
r := bufio.NewReader(body)
if data, err := r.Peek(1024); err == nil {
if _, name, ok := charset.DetermineEncoding(data, ""); ok {
return name
}
}
return "utf-8"
}
// Decode parses the HTML body on the specified encoding and
// returns the HTML Document.
func Decode(body io.Reader, charset string) (interface{}, error) {
if charset == "" {
charset = detectContentCharset(body)
}
e, err := htmlindex.Get(charset)
if err != nil {
return nil, err
}
if name, _ := htmlindex.Name(e); name != "utf-8" {
body = e.NewDecoder().Reader(body)
}
node, err := html.Parse(body)
if err != nil {
return nil, err
}
return node, nil
}

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊
goquery可以滿足您的需求。例如:
import "https://github.com/PuerkitoBio/goquery"
func main() {
d, err := goquery.NewDocument("http://www.google.com")
dh := d.Find("head")
dc := dh.Find("meta[http-equiv]")
c, err := dc.Attr("content") // get charset
// ...
}
更多的操作可以在Document結(jié)構(gòu)中找到。
- 2 回答
- 0 關(guān)注
- 234 瀏覽
添加回答
舉報(bào)