lord_ne

requester.py

Mar 31st, 2021
724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import json
  2. import requests
  3. import time
  4. from datetime import datetime
  5.  
  6. all_fields = [
  7.     "id",
  8.     "title",
  9.     "main_picture",
  10.     "alternative_titles",
  11.     "start_date",
  12.     "end_date",
  13.     "synopsis",
  14.     "mean",
  15.     "rank",
  16.     "popularity",
  17.     "num_list_users",
  18.     "num_scoring_users",
  19.     "nsfw",
  20.     "genres",
  21.     "created_at",
  22.     "updated_at",
  23.     "media_type",
  24.     "status",
  25.     #"my_list_status",
  26.     "num_episodes",
  27.     "start_season",
  28.     "broadcast",
  29.     "source",
  30.     "average_episode_duration",
  31.     "rating",
  32.     "studios",
  33.     #"pictures",
  34.     #"background",
  35.     #"related_anime",
  36.     #"related_manga",
  37.     #"recommendations",
  38.     #"statistics"
  39.     ]
  40.  
  41. def request(access_token, curr_offset):
  42.     url = 'https://api.myanimelist.net/v2/anime/ranking'
  43.     response = requests.get(url,
  44.         headers = {'Authorization': f'Bearer {access_token}'},
  45.         params = {
  46.             'ranking_type' : 'all',
  47.             'limit' : 500,
  48.             'offset' : curr_offset,
  49.             'fields' : ','.join(all_fields)
  50.         })
  51.     response.raise_for_status()
  52.     response.close()
  53.     return response.json()
  54.  
  55. def scrape(access_token):
  56.     date_string = datetime.now().isoformat().replace(':','')
  57.     with open(f'database_{date_string}.json', 'w') as file:
  58.         file.write('[\n')
  59.         delim = ''
  60.         for offset in range(0, 100000, 500):
  61.             print(f'Getting {offset+1} through {offset+500}')
  62.             data = request(access_token, offset)['data']
  63.             if len(data) == 0:
  64.                 break
  65.             for d in data:
  66.                 file.write(delim)
  67.                 delim = ',\n'
  68.                 json.dump(d['node'], file, indent = 4)
  69.             time.sleep(0.3)
  70.         file.write("\n]")
  71.     print('Done')
  72.  
  73. if __name__ == '__main__':
  74.     with open('token.json') as file:
  75.         token = json.load(file)['access_token']
  76.         scrape(token)
  77.  
Advertisement
Add Comment
Please, Sign In to add comment