Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
golang HTML字符集解码_Go - Fatal编程技术网

golang HTML字符集解码

golang HTML字符集解码,go,Go,我正在尝试解码非utf-8编码的HTML页面 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 有没有图书馆可以这样做?我在网上找不到 当然,我可以用goquery和iconv go提取字符集并解码HTML页面,但我尽量不重新发明轮子。可能满足您的需要。e、 g: import "https://github.com/PuerkitoBio/goquery" func main() {

我正在尝试解码非utf-8编码的HTML页面

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

有没有图书馆可以这样做?我在网上找不到

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

可能满足您的需要。e、 g:

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
    // ...
}

更多操作可以在struct中找到。

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
}