4
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?

More than 1 year has passed since last update.

QiitaのAPIでいいねした投稿一覧を取得

Posted at

PythonでQiitaのAPIをコールして、Qiitaのいいねした投稿一覧を取得するように実装してみました。
取得した記事はいいね数降順でソートします。

pip install pandas==1.3.5
pip install requests==2.28.2
pip install openpyxl==3.0.9
get_qiita_article.py
import requests
import pandas as pd
from datetime import datetime as dt


def get_qiita_articles_by_page(page):
    """
    第何ページ目の文章を取得
    @param page ページ目
    @return 文章リストを返す
    """
    url = 'https://qiita.com/api/v2/items'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'
    }
    params = {
        'page': page,
        'per_page': 100,
        'query': 'likes_count:=0'
    }
    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        article = response.json()
        return article
    return None


def get_qiita_articles():
    """
    qiitaの文章を取得

    """
    articles = []
    for i in range(1, 9999):
        top = get_qiita_articles_by_page(i)
        if top:
            articles.extend(top)
        else:
            break
    return articles


def out_put_articels(file_name):
    """
    qiitaの文章を出力
    """
    articles = get_qiita_articles()
    # for index, article in enumerate(articles, start=1):
    #     print(f'{index}. {article.get("title")} - {article.get("likes_count")} likes')
    if articles:
        df = pd.DataFrame(articles)
        df.drop(columns=["id", "rendered_body", "body", "coediting", "comments_count", "created_at", "group", "private", "reactions_count",
                         "stocks_count", "tags", "updated_at", "team_membership", "organization_url_name", "user", "page_views_count"], axis=1, inplace=True)
        df.sort_values(by="likes_count", axis=0, ascending=False, inplace=True)
        df = df[df["likes_count"] > 0]
        df = df.reindex(columns=['title', 'url', 'likes_count'])
        df.to_csv(file_name, encoding='utf-8', index=False)
    else:
        print("文章を取得できなかった!")


if __name__ == '__main__':
    day = dt.now().strftime('%Y%m%d')
    out_put_articels(f'./result_{day}.csv')

更にGithubのActionを利用して、毎日定時的に実行します。

schedule.yml
name: schedule

on:
  schedule:
    - cron: "0 8 * * *"
  push:
    branches:
      - main

jobs:
  excute-python:
    runs-on: ubuntu-latest
    env:
      TZ: Asia/Tokyo

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: 3.x

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: excute python
        run: |
          git config --local user.email "bot@github.com"
          git config --local user.name "bot"
          git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}
          git pull --rebase
          python get_qiita_article.py
          git add .
          git commit -m "update by github action"
          git push

参考

4
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
4
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?