爬蟲自動轉碼,擷取城市列表:城市名稱+URL

來源:互聯網
上載者:User

//下載外掛程式工具
go get -v github.com/gpmgo/gopm

//自動匯入包外掛程式
gopm get -g -v golang.org/x/tools/cmd/goimports

//轉碼外掛程式
gopm get -g -v golang.org/x/text

//自動檢測網頁編碼
gopm get -g -v golang.org/x/net/html

package mainimport (    "net/http"    "io/ioutil"    "fmt"    "golang.org/x/text/transform"    "io"    "golang.org/x/text/encoding"    "golang.org/x/net/html/charset"    "bufio"    "regexp")func main() {    resp, err := http.Get("http://www.zhenai.com/zhenghun")    if err != nil {        panic(err)    }    defer resp.Body.Close()    if resp.StatusCode != http.StatusOK {        fmt.Println("Error:status code", resp.StatusCode)        return    }    e := determinEncoding(resp.Body)    utf8Reader := transform.NewReader(resp.Body, e.NewDecoder())    all, err := ioutil.ReadAll(utf8Reader)    if err != nil {        panic(err)    }    printCityList(all)}func printCityList(contents []byte) {    re := regexp.MustCompile(`<a href="(http://www.zhenai.com/zhenghun/[0-0a-z]+)"[^>]*>([^<]+)</a>`)    matches := re.FindAllSubmatch(contents, -1)    for _, m := range matches {        fmt.Printf("City: %s, URL: %s\n", m[2], m[1])    }    fmt.Printf("Matches found:%d\n", len(matches))}func determinEncoding(r io.Reader) encoding.Encoding {    bytes, err := bufio.NewReader(r).Peek(1024)    if err != nil {        panic(err)    }    e, _, _ := charset.DetermineEncoding(bytes, "")    return e}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.