1
1

Pythonを使って楽天ディレクトリIDを抽出する

Posted at

楽天のディレクトリIDを抽出する

楽天のディレクトリIDを抽出してコンソールに表示させるコード

※楽天ではカテゴリをディレクトリと呼んでいる

第一階層のディレクトリIDだけ抽出

#楽天ジャンルIDを第一階層を取得して表示する

import requests

RAKUTEN_GENRE_API_URL = 'https://app.rakuten.co.jp/services/api/IchibaGenre/Search/20140222'

def get_genre(genre_id=0, format_version=2, app_id='YOUR_APP_ID'):
    params = {
        'applicationId': app_id,
        'formatVersion': format_version,
        'genreId': genre_id,
    }
    r = requests.get(RAKUTEN_GENRE_API_URL, params=params)
    item_data = r.json()
    return item_data

def print_genres(genres, indent=0):
    for genre in genres:
        print('  ' * indent + f"{genre['genreId']}: {genre['genreName']}")
        if 'children' in genre:
            print_genres(genre['children'], indent + 1)

if __name__ == "__main__":
    app_id = 'YOUR_APP_ID'
    top_level_genres = get_genre(app_id=app_id)['children']
    print_genres(top_level_genres)

第2階層まで抽出する

#楽天ジャンルIDを第二階層まで取得して表示する

import requests

RAKUTEN_GENRE_API_URL = 'https://app.rakuten.co.jp/services/api/IchibaGenre/Search/20140222'

def get_genre(genre_id=0, format_version=2, app_id='YOUR_APP_ID'):
    params = {
        'applicationId': app_id,
        'formatVersion': format_version,
        'genreId': genre_id,
    }
    r = requests.get(RAKUTEN_GENRE_API_URL, params=params)
    item_data = r.json()
    return item_data

def print_genres(genres, indent=0):
    for genre in genres:
        print('  ' * indent + f"{genre['genreId']}: {genre['genreName']}")
        if 'children' in genre:
            child_genres = get_genre(genre['genreId'])['children']
            print_genres(child_genres, indent + 1)

if __name__ == "__main__":
    app_id = 'YOUR_APP_ID'
    top_level_genres = get_genre(app_id=app_id)['children']
    for genre in top_level_genres:
        print(f"{genre['genreId']}: {genre['genreName']}")
        child_genres = get_genre(genre['genreId'])['children']
        print_genres(child_genres, 1)

YOUR_APP_IDには自身のアプリIDを使用する

  • 確認は以下のURL
  • アプリID発行方法は省略

Rakuten Developers(アプリ情報確認ページ)
https://webservice.rakuten.co.jp/app/list

以上

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