golang HTML字符集解码



我正在尝试解码NOTutf-8编码的HTML页面。

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

有图书馆能做到这一点吗?我在网上找不到。

p.S当然,我可以用goquery和iconv-go提取字符集并解码HTML页面,但我尽量不重新发明轮子。

Golang正式提供扩展包:字符集和编码。

下面的代码确保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
}

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结构找到更多操作。

最新更新