LoginSignup
36
31

More than 3 years have passed since last update.

【Go】Webスクレイピングのやり方

Last updated at Posted at 2019-09-22

関連

はじめに

GoでWebスクレイピングをしたい時にはgoqueryという便利なパッケージがある
ただ、文字コードがEUC-JPのサイト等に使おうとすると文字化けするので、その辺りの文字コード変換を自前で実装する必要がある。
goqueryの使い方については以下の記事を参照。

準備

必要なパッケージをダウンロードする。

$ go get -u github.com/PuerkitoBio/goquery
$ go get -u github.com/saintfish/chardet
$ go get -u golang.org/x/net/html/charset

サンプルコード

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"

    "github.com/PuerkitoBio/goquery"
    "github.com/saintfish/chardet"
    "golang.org/x/net/html/charset"
)

func main() {
    url := "https://fortune.yahoo.co.jp/12astro/20190922/scorpio.html"

    // Getリクエスト
    res, _ := http.Get(url)
    defer res.Body.Close()

    // 読み取り
    buf, _ := ioutil.ReadAll(res.Body)

    // 文字コード判定
    det := chardet.NewTextDetector()
    detRslt, _ := det.DetectBest(buf)
    fmt.Println(detRslt.Charset)
    // => EUC-JP

    // 文字コード変換
    bReader := bytes.NewReader(buf)
    reader, _ := charset.NewReaderLabel(detRslt.Charset, bReader)

    // HTMLパース
    doc, _ := goquery.NewDocumentFromReader(reader)

    // titleを抜き出し
    rslt := doc.Find("title").Text()
    fmt.Println(rslt)
    // => さそり座(蠍座) 今日の運勢 - Yahoo!占い
}

参考

36
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
31