LoginSignup
1
0

More than 1 year has passed since last update.

【#52 エンジニア転職学習】goqueryでhref情報をスクレイピング

Posted at

はじめに

富山県に住んでいるChikaといいます。
毎日投稿を目標に、バックエンドエンジニア転職に向けた学習内容をアウトプットします。

引き続きスクレイピングのプロジェクトをつくっていきます。

バックエンドエンジニアになるまでの学習内容は以前投稿した以下の記事を基にしています。

本日の学習内容

本日は1つ目のタスクとしてURL一覧を取得するハンドラー部分を作成しました。

  • goqueryでURL一覧を取得するハンドラー作成 ←Topics!!

goqueryでURL一覧を取得するハンドラー作成

対象である「マイナビ転職」の求人一覧ページ(https://tenshoku.mynavi.jp/list/)から、各求人詳細ページへのリンクURLを取得するところから始めます。
添付画像の/jobinfo ~ /をHTMLから取得してきます。
image.png

手順はざっくり以下のとおりです。

  1. http.GetとBodyでページ情報を取得
  2. goquery.NewDocumentFromReaderでインターフェース作成
  3. FindとAttrでHTMLタグとhrefで取得したい情報まで指定
  4. SplitAfterNで文字列を区切る

実行すると↓のように綺麗に抽出できました。

image.png

main.go
package main

import (
	"fmt"
	"log"
	"net/http"

	"strings"

	"github.com/PuerkitoBio/goquery"
)

func main() {
	url := "https://tenshoku.mynavi.jp/list/pg2/"
	res, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
	}

	doc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		log.Fatal(err)
	}

	doc.Find("div.cassetteRecruit").Each(func(i int, s *goquery.Selection) {
		href, _ := s.Find("p.cassetteRecruit__copy > a").Attr("href")
		href = string([]rune(href))
		mynaviurl := strings.SplitAfterN(href, "/", 3)
		fmt.Printf("Review %d: %s\n", i, mynaviurl[0]+mynaviurl[1])
	})
}

使用している教材はこちら↓

おわりに

最後までお読みいただきありがとうございました。
アドバイス・応援コメント等いただけますと幸いです。

1
0
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
1
0