LoginSignup
8
11

More than 5 years have passed since last update.

スクレイピングでQiitaの「いいね」一覧を取得する

Last updated at Posted at 2016-12-02

はじめに

まず初めに書いて置きますが、僕は文章を書くのは得意ではないので読みにくかったらもうしわけありません。
さて、私は、いいねをストック代わりに使っていたので、いいねの一覧を見ることができないと知って、非常に、憤っております。twitterやQiitaでも、多くの方々が悩んでいるようです。1 2
というわけで、pythonでスクレイピングして、いいね一覧を取得します。

導入

python3をインストールしたら、pipコマンドでrequests、BeautifulSoup4,progressbar2
をインストールしてください

コード

記事一覧を取得して、results.jsonファイルに保存します。

# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
import requests
from time import sleep
import json
from progressbar import ProgressBar

# Qiitaにlogin
payload = {
    'utf8': '✓',
    'identity': 'lovemuffim114',  # ユーザー名
    'password': 'tkhr2783'  # パスワード
}

# authenticity_tokenの取得
s = requests.Session()
r = s.get('https://qiita.com')
soup = BeautifulSoup(r.text, "html.parser")
auth_token = soup.find(attrs={'name': 'authenticity_token'}).get('value')
payload['authenticity_token'] = auth_token

# ログイン
s.post('https://qiita.com/login', data=payload)

# 結果を保存するための辞書
results = dict()

searchId = 1000000
param = {"before": searchId, "type": "id"}
# 記事数を取得
maxId = s.get("http://qiita.com/api/public", params=param).json()[0]["id"]
bar = ProgressBar(min_value=0, max_value=maxId)  # 最大値をセット

try:  # 読み込む記事がなくなるとエラー
    while True:
        param = {"before": searchId, "type": "id"}
        # 記事リスト取得
        j = s.get("http://qiita.com/api/public", params=param).json()

        # resultsに「いいね」かつストックしていない記事を追加します。
        # "url"以外に、"uuid"も指定できます。
        results.update({i["title"]: i["url"] for i in j if i["liked"] and not i["stocked"]})

        searchId = j[-1]["id"]
        bar.update(maxId - searchId)  # プログレスバー更新
        sleep(1)  # sleep(1秒)小数点が使えます。
finally:
    print(results)

    # results.jsonに保存
    with open("results.json", "a") as f:
        json.dump(results, f, ensure_ascii=False, indent=4, separators=(',', ': '))

以上です。結果は、

{
    "【narou4j】Javaで小説家になろうの小説取得ライブラリをつくった": "863aa22a29db16463e52",
    "ViewHolderを使わないでListViewを高速化する": "28f8be64d39b20e69552",
    "【narou4j】なろうAPIのJavaラッパーライブラリをつくった": "6c050593f45174056005",
    "水耕栽培セットを自作してみた。": "5d60c14d560ecf518a4e",
    "RxJava + Flux (+ Kotlin)によるAndroidアプリ設計": "cbf304891daec87ba5b7",
    "RxJavaでEventBusを作った": "a4ece37834446c9a39c8"
}

のように保存されます。Qiitaへのログインについては、Pythonでのウェブサイトへのログインを使用させてもらいました。

注釈

8
11
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
8
11