#!/usr/bin/env python3 # mal-archive.py import requests # for requests import browser_cookie3 # for cookies from bs4 import BeautifulSoup # for html parsing from pathlib import Path # for Path import tarfile, gzip # for archiving import shutil, os # for moving and removing files import sys # for exit() from datetime import datetime # for getting the current date # Get current date in DD-MM-YYYY format current_date = datetime.now().strftime('%d-%m-%Y') # Make a path object to where you want to save your lists animelist_path = Path.home() / 'Downloads' / 'anime-list' # Get cookies from a browser cookies = browser_cookie3.firefox() # Make strings for anime and manga lists filename, also for an archive animelist_filename = 'anime-' + current_date + '.xml.gz' mangalist_filename = 'manga-' + current_date + '.xml.gz' archive_name = 'list-' + current_date + '.tar' def extract_and_remove(filename): try: with gzip.open(filename, 'rb') as gz_file: extracted_data = gz_file.read() except BadGzipFile: print('An error occured, exiting...') sys.exit() filename = os.path.splitext(filename)[0] # Determine the output file name without the .gz extension with open(filename, 'wb') as out_file: # Write the extracted data to the output file out_file.write(extracted_data) os.remove(filename + '.gz') print('Downloading lists...') r = requests.get('https://myanimelist.net/panel.php?go=export', cookies=cookies) soup = BeautifulSoup(r.text, features='html.parser') csrfToken = soup.find('meta', attrs={'name': 'csrf_token'})['content'] headers = { 'content-type': 'application/x-www-form-urlencoded' } data = { 'type': 1, # anime 'subexport': 'Export+My+List', 'csrf_token': csrfToken } response = requests.post('https://myanimelist.net/panel.php?go=export2', data=data, headers=headers, cookies=cookies) # Make the request with open(animelist_filename, "wb") as f: # Save the data to a file f.write(response.content) data['type'] = 2 # manga response = requests.post('https://myanimelist.net/panel.php?go=export2', data=data, headers=headers, cookies=cookies) with open(mangalist_filename, "wb") as f: # Save the data to a file f.write(response.content) print('Making an archive...') # Make an archive, add anime and manga lists there, remove the files afterwards extract_and_remove(animelist_filename) extract_and_remove(mangalist_filename) with tarfile.open(archive_name, "w:gz") as archive: for file in [animelist_filename[:-3], mangalist_filename[:-3]]: # Remove .gz at the end archive.add(file) os.remove(file) try: # Move the archive to ~/Downloads/anime-list directory shutil.move(archive_name, animelist_path) except OSError: print("Old list file found, removing...") os.remove(animelist_path / archive_name) shutil.move(archive_name, animelist_path) print('Lists successfully exported to ' + str(animelist_path))