0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Qiita・Zenn・note・dev.to の反応を1本のスクリプトで集計する【標準ライブラリのみ・コピペ用】

0
Posted at

複数の媒体に技術記事を書いていると、どこで何が読まれたのかが分からなくなります。媒体ごとに管理画面を開いて、目で見て、なんとなく把握する。それを毎週やるのは続きません。

4媒体の反応を1本のスクリプトで集めて、CSVに履歴として積む形にしました。3か月ほど毎週回しています。標準ライブラリだけで動くので、GitHub Actions に置くときに pip install が要りません。

先に、このスクリプトでできることを書きます。

  • Qiita / Zenn / dev.to / note から、記事ごとの反応・コメント・ビュー・ストックを取得
  • 実行日ごとのスナップショットとして CSV に追記(時系列で伸びが追える)
  • 最新の一覧を Markdown で出力(反応数の降順、反応率つき)
  • 媒体ごとの「PV・反応・反応率」を集計して表示

そして、この記事のいちばんの中身は、4媒体ぶんのAPIの癖です。 実際に叩くと、それぞれ違うところで詰まります。そこを全部書きます。


スクリプト全文

collect_reactions.py として保存します。冒頭のユーザー名だけ自分のものに書き換えてください。

#!/usr/bin/env python3
"""
collect_reactions.py
Qiita / Zenn / dev.to / note の記事反響を1つに束ねて集計する。
標準ライブラリのみ(requests 不要 → Actions で pip install 不要)
"""

import csv
import json
import os
import sys
import time
import urllib.request
import urllib.error
from datetime import date
from pathlib import Path

# ------------------------------------------------------------------ 設定
QIITA_USER   = "your_qiita_id"
ZENN_USER    = "your_zenn_id"
DEVTO_USER   = "your_devto_id"
NOTE_URLNAME = "your_note_id"      # note.com/<ここ>

OUT_DIR     = Path(os.environ.get("OUT_DIR", "."))
HISTORY_CSV = OUT_DIR / "reactions_history.csv"
LATEST_MD   = OUT_DIR / "reactions_latest.md"

UA = "reactions-collector/1.0"
TIMEOUT = 20


def _get(url, headers=None):
    req = urllib.request.Request(url, headers={"User-Agent": UA, **(headers or {})})
    with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
        return json.loads(r.read().decode("utf-8"))


def _record(platform, title, url, published_at, reactions, comments,
            views=None, stock=None):
    return {
        "platform": platform,
        "title": (title or "").strip(),
        "url": url,
        "published_at": (published_at or "")[:10],
        "published_at_full": (published_at or ""),   # 初速の分析用に時刻も残す
        "reactions": reactions if reactions is not None else "",
        "comments": comments if comments is not None else "",
        "views": views if views is not None else "",
        "stock": stock if stock is not None else "",
    }


# ------------------------------------------------------------------ Qiita
def _qiita_item_detail(item_id, headers):
    """個別APIを1回叩いて PV とストック数を取る。
    page_views_count は一覧APIでは null が返るので、ここから取る。
    投稿者本人が認証している場合のみ値が入る。
    失敗しても集計は続けたいので (None, None) を返す。"""
    try:
        item = _get(f"https://qiita.com/api/v2/items/{item_id}", headers)
    except Exception as e:
        print(f"[warn] qiita detail {item_id}: {type(e).__name__}", file=sys.stderr)
        return None, None
    return item.get("page_views_count"), item.get("stocks_count")


def _qiita_stock_count(item_id, headers):
    """stocks_count が取れなかったときのフォールバック。
    /stockers をページングして数える。"""
    total, page = 0, 1
    while True:
        url = (f"https://qiita.com/api/v2/items/{item_id}/stockers"
               f"?page={page}&per_page=100")
        try:
            stockers = _get(url, headers)
        except Exception:
            return None
        if not stockers:
            break
        total += len(stockers)
        if len(stockers) < 100:
            break
        page += 1
        time.sleep(0.2)
    return total


def fetch_qiita():
    out, headers = [], {}
    token = os.environ.get("QIITA_TOKEN")
    if token:
        headers["Authorization"] = f"Bearer {token}"
    want_detail = bool(token)   # 未認証は 60req/h なので取りにいかない
    if not want_detail:
        print("[info] QIITA_TOKEN 未設定 → PV・ストックは取得しません", file=sys.stderr)

    page = 1
    while True:
        url = (f"https://qiita.com/api/v2/users/{QIITA_USER}/items"
               f"?page={page}&per_page=100")
        items = _get(url, headers)
        if not items:
            break
        for it in items:
            views, stock = None, None
            if want_detail:
                views, stock = _qiita_item_detail(it.get("id"), headers)
                time.sleep(0.2)
                if stock is None:
                    stock = _qiita_stock_count(it.get("id"), headers)
                    time.sleep(0.2)
            out.append(_record(
                "qiita", it.get("title"), it.get("url"), it.get("created_at"),
                it.get("likes_count"), it.get("comments_count"),
                views=views, stock=stock,
            ))
        if len(items) < 100:
            break
        page += 1
        time.sleep(0.5)
    return out


# ------------------------------------------------------------------ Zenn(非公式)
def fetch_zenn():
    out, page = [], 1
    while True:
        url = (f"https://zenn.dev/api/articles"
               f"?username={ZENN_USER}&order=latest&page={page}")
        data = _get(url)
        for a in data.get("articles", []):
            out.append(_record(
                "zenn", a.get("title"),
                f"https://zenn.dev{a.get('path','')}",
                a.get("published_at"),
                a.get("liked_count"), a.get("comments_count"),
            ))
        nxt = data.get("next_page")
        if not nxt:
            break
        page = nxt          # ← 連番ではなく、返ってきた値をそのまま使う
        time.sleep(0.5)
    return out


# ------------------------------------------------------------------ dev.to(公式 Forem API)
def fetch_devto():
    out = []
    api_key = os.environ.get("DEVTO_API_KEY")
    page = 1
    while True:
        if api_key:
            # 自分の記事 → PV(page_views_count) も取れる
            url = f"https://dev.to/api/articles/me/published?page={page}&per_page=100"
            arts = _get(url, {"api-key": api_key})
        else:
            url = (f"https://dev.to/api/articles"
                   f"?username={DEVTO_USER}&page={page}&per_page=100")
            arts = _get(url)
        if not arts:
            break
        for a in arts:
            out.append(_record(
                "devto", a.get("title"), a.get("url"), a.get("published_at"),
                a.get("public_reactions_count"), a.get("comments_count"),
                a.get("page_views_count"),   # api_key 無しだと None
            ))
        if len(arts) < 100:
            break
        page += 1
        time.sleep(0.5)
    return out


# ------------------------------------------------------------------ note(非公式)
def fetch_note():
    out, page = [], 1
    while True:
        url = (f"https://note.com/api/v2/creators/{NOTE_URLNAME}"
               f"/contents?kind=note&page={page}")
        data = _get(url).get("data", {})
        contents = data.get("contents", [])
        for c in contents:
            # フィールド名が揺れるので両対応にしておく
            likes = c.get("likeCount", c.get("like_count"))
            comments = c.get("commentCount", c.get("comment_count"))
            key = c.get("key")
            out.append(_record(
                "note", c.get("name"),
                f"https://note.com/{NOTE_URLNAME}/n/{key}" if key else None,
                c.get("publishAt") or c.get("publish_at"),
                likes, comments,
            ))
        if data.get("isLastPage", True) or not contents:
            break
        page += 1
        time.sleep(0.7)     # 非公式なので少し丁寧に
    return out


# ------------------------------------------------------------------ 出力
FETCHERS = {
    "qiita": fetch_qiita,
    "zenn": fetch_zenn,
    "devto": fetch_devto,
    "note": fetch_note,
}
FIELDS = ["snapshot_date", "platform", "title", "url",
          "published_at", "published_at_full",
          "reactions", "comments", "views", "stock"]


def _append_history(rows):
    """履歴CSVへ追記。既存ヘッダが FIELDS と違う(列を増やした直後など)場合は、
    旧行に空欄を補完してヘッダごと書き直してから追記する。列ズレ防止。"""
    def _w(r):
        return {k: r.get(k, "") for k in FIELDS}

    if not HISTORY_CSV.exists():
        with HISTORY_CSV.open("w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=FIELDS)
            w.writeheader()
            for r in rows:
                w.writerow(_w(r))
        return

    with HISTORY_CSV.open("r", newline="", encoding="utf-8") as f:
        existing_header = next(csv.reader(f), [])

    if existing_header == FIELDS:
        with HISTORY_CSV.open("a", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=FIELDS)
            for r in rows:
                w.writerow(_w(r))
        return

    with HISTORY_CSV.open("r", newline="", encoding="utf-8") as f:
        old_rows = list(csv.DictReader(f))
    tmp = HISTORY_CSV.with_suffix(".csv.tmp")
    with tmp.open("w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore")
        w.writeheader()
        for r in old_rows:
            w.writerow({k: r.get(k, "") for k in FIELDS})
        for r in rows:
            w.writerow(_w(r))
    tmp.replace(HISTORY_CSV)
    print(f"[migrate] 列を {len(existing_header)}→{len(FIELDS)} に移行", file=sys.stderr)


def _rate(reactions, views):
    """PVがある行だけ反応率(%)を返す。無い/0なら None。"""
    if isinstance(reactions, int) and isinstance(views, int) and views > 0:
        return reactions / views * 100
    return None


def _platform_stats(rows):
    """PVが取れている媒体について、反応率などを出す。"""
    lines = []
    for pf in ("qiita", "devto"):
        sub = [r for r in rows if r["platform"] == pf]
        v = sum(r["views"] for r in sub if isinstance(r["views"], int))
        if not v:
            continue
        rc = sum(r["reactions"] for r in sub if isinstance(r["reactions"], int))
        st = sum(r["stock"] for r in sub if isinstance(r["stock"], int))
        over5 = sum(1 for r in sub
                    if isinstance(r["reactions"], int) and r["reactions"] >= 5)
        line = (f"{pf}: PV {v} / 反響 {rc}(率 {rc / v * 100:.2f}%)"
                f" / 反響5以上 {over5}/{len(sub)}本")
        if st:
            line += f" / ストック {st}"
        lines.append(line)
    return lines


def main():
    today = date.today().isoformat()
    rows = []
    for name, fn in FETCHERS.items():
        try:
            recs = fn()
            for r in recs:
                r["snapshot_date"] = today
            rows.extend(recs)
            print(f"[ok]   {name:6s} {len(recs):3d} 件")
        except urllib.error.HTTPError as e:
            print(f"[skip] {name:6s} HTTP {e.code} {e.reason}", file=sys.stderr)
        except Exception as e:
            print(f"[skip] {name:6s} {type(e).__name__}: {e}", file=sys.stderr)

    if not rows:
        print("取得0件。ユーザー名の設定を確認してください。", file=sys.stderr)
        sys.exit(1)

    _append_history(rows)

    def rkey(r):
        return r["reactions"] if isinstance(r["reactions"], int) else -1

    rows_sorted = sorted(rows, key=rkey, reverse=True)
    total = sum(r["reactions"] for r in rows if isinstance(r["reactions"], int))

    with LATEST_MD.open("w", encoding="utf-8") as f:
        f.write(f"# 記事反響まとめ({today})\n\n")
        f.write(f"全{len(rows)}記事 / 反響合計 {total}\n\n")
        stats = _platform_stats(rows)
        if stats:
            for s in stats:
                f.write(f"- {s}\n")
            f.write("\n")
        f.write("| 媒体 | 反響 | コメント | Stock | PV | 反響率 | タイトル |\n")
        f.write("|---|--:|--:|--:|--:|--:|---|\n")
        for r in rows_sorted:
            title = r["title"][:42]
            link = f"[{title}]({r['url']})" if r["url"] else title
            rate = _rate(r["reactions"], r["views"])
            rate_s = f"{rate:.1f}%" if rate is not None else ""
            f.write(f"| {r['platform']} | {r['reactions']} | {r['comments']} "
                    f"| {r['stock']} | {r['views']} | {rate_s} | {link} |\n")

    for s in _platform_stats(rows):
        print(f"[stat] {s}")
    print(f"\n→ {HISTORY_CSV}(追記)\n→ {LATEST_MD}")


if __name__ == "__main__":
    main()

実行はこれだけです。

export QIITA_TOKEN=xxxxxxxx      # 任意(あるとPV・ストックが取れる)
export DEVTO_API_KEY=xxxxxxxx    # 任意(あるとPVが取れる)
python3 collect_reactions.py

ここからが本題:媒体ごとのAPIの癖

4つとも、違うところで詰まります。実際に踏んだ順に書きます。

Qiita:PVは一覧APIでは取れない

いちばんの落とし穴がこれでした。

記事一覧 /api/v2/users/{user}/items は、page_views_count というフィールドを持っています。ただ、中身は null です。 一覧では返ってきません。

PVを取るには、記事ごとに /api/v2/items/{id} を叩きます。しかも、値が入るのは投稿者本人が認証している場合だけです。他人の記事のPVは取れません。

# ❌ これでは PV が null のまま
items = _get(f"https://qiita.com/api/v2/users/{user}/items")

# ✅ 個別APIを、本人のトークンで叩く
item = _get(f"https://qiita.com/api/v2/items/{item_id}",
            {"Authorization": f"Bearer {token}"})
item.get("page_views_count")

記事が60本なら61リクエストです。認証ありのレート上限は1時間1000回なので、数百本まではこの方法で足ります。

ストック数も同じ場所から取れます。 stocks_count が返ればそれを使い、返らなければ /items/{id}/stockers をページングして数える、というフォールバックにしてあります。仕様が揺れている部分なので、両方用意しておくのが安全でした。

Zenn:next_page は連番ではない

Zennには公式APIがないので、/api/articles を使います。非公式なので、いつ変わってもおかしくない前提で扱います。

ここでの癖は、ページングです。

# ❌ 連番でインクリメントすると、途中で取りこぼす
page += 1

# ✅ レスポンスの next_page をそのまま次のリクエストに使う
nxt = data.get("next_page")
if not nxt:
    break
page = nxt

next_page が null になったら終わり、という判定にします。件数で判断すると、境界でずれます。

dev.to:api-key があるとPVが取れる

ここは公式APIなので、素直です。ただ、エンドポイントが2つあります。

# 誰でも叩ける(PVは取れない)
/api/articles?username=xxx

# 自分の記事(api-key ヘッダが要る。PVが取れる)
/api/articles/me/published

page_views_count が欲しいなら後者です。ヘッダ名が Authorization ではなく api-key なのが、少し珍しいところでした。

arts = _get(url, {"api-key": api_key})

note:フィールド名が揺れる

noteも非公式です。/api/v2/creators/{urlname}/contents?kind=note で記事一覧が取れます。

癖は、フィールド名がキャメルケースとスネークケースで揺れることでした。時期によって likeCount だったり like_count だったりします。

# 両対応にしておく
likes    = c.get("likeCount", c.get("like_count"))
comments = c.get("commentCount", c.get("comment_count"))

終了判定は isLastPage を見ます。ここも、無かった場合に備えて既定値を True にしてあります(取れなければ1ページで止まる、という安全側の倒し方です)。

記事のURLは、レスポンスに完全な形では入っていません。 key を取って、自分で組み立てます。

f"https://note.com/{NOTE_URLNAME}/n/{key}"

番外:Hashnode は無料APIが終わりました

以前は Hashnode も集めていましたが、2026年5月13日に無料のGraphQL APIが廃止され、Pro限定になりました。

その前にも、いくつか癖がありました。CDN がボット系の User-Agent を弾くので、POST だけブラウザ寄りのUAにする必要があった。POSTが301でGETに化けてHTMLを掴む事故があったので、リダイレクトを禁止するオープナーを使っていた。

いまはトークンが無ければ自動でスキップする形にして、対象から外しています。非公式APIや無料枠に依存する部分は、こうやって静かに消えることがあります。 集計スクリプトは、1媒体が落ちても他が動く作りにしておくと長持ちします。


履歴CSVを、列の追加に強くする

最初は反応数だけを取っていて、あとからPVとストックの列を足しました。このとき、既存のCSVと列がずれます。

素直に追記すると、古い行が8列、新しい行が10列になって、pandas で読んだときに壊れます。

なので、ヘッダが変わっていたら1回だけ書き直す処理を入れました。

with HISTORY_CSV.open("r", newline="", encoding="utf-8") as f:
    existing_header = next(csv.reader(f), [])

if existing_header == FIELDS:
    # そのまま追記
else:
    # 旧行を読んで、新しい FIELDS に空欄を補完して書き直し、そこへ追記

extrasaction="ignore" を付けておくと、旧CSVに余計な列があっても落ちません。

集計スクリプトは、あとから列が増えます。 最初からその前提で書いておくと、追加のたびに手作業でCSVを直さずに済みます。


反応率を出す(ここがいちばん効きました)

絶対数だけを見ていると、母数の差が全部消えます。PVが取れる媒体だけでも、率を出しておくと見え方が変わります。

qiita: PV 29530 / 反響 29(率 0.10%) / 反響5以上 0/64本 / ストック 24
devto: PV 5244  / 反響 205(率 3.91%)/ 反響5以上 15/24本

自分の場合、この2行を出すまで3か月かかりました。反応数だけを見て「Qiitaは自分に合っていない」と判断していたのに、PVでは4媒体の中でいちばん多かった、というのが分かったのは、この行を足した日です。

検索から来る媒体は、そもそもボタンを押す動線がありません。押された数で評価すると、必ず誤読します。媒体ごとに、見る列を変える必要があります。


GitHub Actions で毎週回す

pip install が要らないので、ワークフローは短く済みます。

# .github/workflows/collect.yml
name: Collect reactions

on:
  schedule:
    - cron: '0 0 * * 1'      # 毎週月曜 09:00 JST
  workflow_dispatch:          # 手動実行も可

permissions:
  contents: write

jobs:
  collect:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Collect
        env:
          QIITA_TOKEN: ${{ secrets.QIITA_TOKEN }}
          DEVTO_API_KEY: ${{ secrets.DEVTO_API_KEY }}
        run: python3 collect_reactions.py

      - name: Commit
        run: |
          git config user.name  "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add reactions_history.csv reactions_latest.md
          git diff --staged --quiet || git commit -m "chore: reactions $(date +%F)"
          git push

git diff --staged --quiet || を挟んでいるのは、変化がなかった週にコミットを空振りさせないためです。これが無いと、毎週「変更なし」で失敗します。

トークンは Settings → Secrets and variables → Actions に登録します。QIITA_TOKEN のスコープは read_qiita だけで足ります。


集めたあと、何を見るか

CSVに履歴が溜まると、こういうことが分かります。

公開直後だけ伸びる記事と、あとから伸びる記事が分かれます。 フィードで流れる媒体は前者、検索で来る媒体は後者でした。自分の場合、数か月更新していない媒体のPVが、いまも増え続けています。

5以上の記事が何本あるか、を見るようになりました。合計だけ見ていると、1本の当たりに全部引っ張られます。分布で見ないと、実態が分かりません。

published_at_full(時刻まで)を残しているのは、公開時刻と初速の関係を見るためです。まだ結論は出ていませんが、時刻を捨ててしまうと後から検証できないので、最初から取っておくことにしました。


早見でまとめ

  • Qiitaの page_views_count は一覧APIでは null。個別API /items/{id} を本人のトークンで叩く
  • Qiitaのストックは stocks_count が返れば使い、返らなければ /items/{id}/stockers をページング
  • Zennは非公式API。ページングは連番ではなく、レスポンスの next_page をそのまま使う
  • dev.toでPVを取るなら /api/articles/me/published。ヘッダ名は api-key
  • noteは非公式API。likeCount / like_count の揺れに両対応。URLは key から自分で組む
  • Hashnodeは2026-05-13に無料API廃止。1媒体が落ちても他が動く作りにしておく
  • 履歴CSVは、あとから列が増える前提で。ヘッダ不一致を検出して1回だけ書き直す
  • 絶対数だけでなく率を出す。母数が違う媒体を同じ列で比べない
  • Actionsは pip install 不要にすると短く済む。空コミットは git diff --staged --quiet || で回避

集計を始めた当初は、数字を眺めて満足していました。3か月続けてみて、測る対象を間違えていると、続けたぶんだけ判断が歪むことが分かりました。スクリプトを書くより、何を列に持つかを決めるほうが大事だったと思います。

役に立ったらストックして、集計を始めるとき見返してください。


ふだんはraplsworks.comで、WordPressプラグイン開発やClaude Codeまわりのことを書いています。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?