Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
19
Help us understand the problem. What is going on with this article?
@kou_pg_0131

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

More than 1 year has passed since last update.

関連

はじめに

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!占い
}

参考

19
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
kou_pg_0131
Goが好き

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
19
Help us understand the problem. What is going on with this article?