Abu3safeer

get anidb needed columns from html file

Sep 2nd, 2024
441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.75 KB | None | 0 0
  1. from bs4 import BeautifulSoup
  2. from pathlib import Path
  3. import sqlite3
  4. import concurrent.futures
  5.  
  6. def strip_check(text):
  7.     if isinstance(text, str):
  8.         return text.strip()
  9.     else:
  10.         return ""
  11.  
  12. needed_data = []
  13.  
  14. html_files = Path().rglob('anime/*.html')
  15.  
  16.  
  17. def fetch_records(file_path):
  18.     # Read the HTML file
  19.     with open(file_path, 'r', encoding='utf-8') as file:
  20.         content = file.read()
  21.  
  22.     print("processing: " + file_path.name)
  23.    
  24.     # Parse the HTML content
  25.     soup = BeautifulSoup(content, 'html.parser')
  26.     anime = {
  27.             "ID": "",
  28.             "anidbID": "",
  29.             "title": "",
  30.             "type": "",
  31.             "startdate": "",
  32.             "enddate": "",
  33.             "related": "",
  34.             "creators": "",
  35.             "description": "",
  36.             "rating": "",
  37.             "picture": "",
  38.             "categories": "",
  39.             "characters": "",
  40.             "epnos": "",
  41.             "airdates": "",
  42.             "episodetitles": "",
  43.             "createddate": "2024-08-30 14:39:08",
  44.         }
  45.  
  46.     # Anime ID and anidbID:
  47.     anime['ID'] = file_path.name.replace('.html', '')
  48.     anime['anidbID'] = file_path.name.replace('.html', '')
  49.     #print('Anime ID and anidbID are: ' + anime['anidbID'])
  50.  
  51.     # Anime title
  52.     anime_title = soup.select_one('h1.anime')
  53.     if(anime_title and hasattr(anime_title,'text')):
  54.         anime['title'] = strip_check(anime_title.text[7:])
  55.     else:
  56.         anime['title'] = "Title for Anime No." + anime['anidbID'] = file_path.name.replace('.html', '')
  57.     #print('Anime title is: ' + anime['title'])
  58.  
  59.     # Anime type
  60.     anime_type = soup.select_one('tr.type td')
  61.     if(anime_type and hasattr(anime_type, 'text')):
  62.         anime['type'] = strip_check(anime_type.text.split(',')[0])
  63.     else:
  64.         anime['type'] = "Anime"
  65.     #print('Anime type is: ' + anime['type'])
  66.  
  67.     # Anime startdate
  68.     anime_startdata = soup.select_one('tr.year span[itemprop="startDate"]')
  69.     if(anime_startdata and hasattr(anime_startdata, 'content')):
  70.         anime['startdate'] = strip_check(anime_startdata['content'])
  71.     else:
  72.         anime_startdata = soup.select_one('tr.year span[itemprop="datePublished"]')
  73.         if(anime_startdata and hasattr(anime_startdata, 'content')):
  74.             anime['startdate'] = strip_check(anime_startdata['content'])
  75.         else:
  76.             anime['startdate'] = '1999-12-30'
  77.     #print('Anime startdate is: ' + anime['startdate'])
  78.  
  79.     # Anime enddate
  80.     anime_enddate = soup.select_one('tr.year span[itemprop="endDate"]')
  81.     if(anime_enddate and hasattr(anime_enddate,'content')):
  82.         anime['enddate'] = strip_check(anime_enddate['content'])
  83.     else:
  84.         anime_enddate = soup.select_one('tr.year span[itemprop="datePublished"]')
  85.         if(anime_enddate and hasattr(anime_enddate,'content')):
  86.             anime['enddate'] = strip_check(anime_enddate['content'])
  87.         else:
  88.             anime['enddate'] = anime['startdate']
  89.     #print('Anime endDate is: ' + anime['enddate'])
  90.  
  91.     # Anime related
  92.     related_anime_list = soup.select('div.relations.direct a.name-colored')
  93.     for related_anime in related_anime_list:
  94.         anime['related'] += strip_check(related_anime.text) + '|'
  95.     if anime['related'].endswith('|'):
  96.         anime['related'] = anime['related'][:-1]
  97.     #print('Anime related is|are: ' + anime['related'])
  98.  
  99.  
  100.     # Anime creators
  101.     creators_list = soup.select('div.extra table.stafflist td.creator a')
  102.     for creator in creators_list:
  103.         anime['creators'] += strip_check(creator.text) + '|'
  104.     if anime['creators'].endswith('|'):
  105.         anime['creators'] = anime['creators'][:-1]
  106.     #print('Anime creators is|are: ' + anime['creators'])
  107.  
  108.     # Anime description
  109.     description = soup.select_one('div[itemprop="description"]')
  110.     if(description and hasattr(description, 'text')):
  111.         anime['description'] = strip_check(description.text)
  112.     else:
  113.         anime['description'] = "No description"
  114.     #print('Anime description is: ' + anime['description'])
  115.  
  116.     # Anime rating
  117.     rating = soup.select_one('tr.rating span[itemprop="ratingValue"]')
  118.     if(rating and hasattr(rating, 'text')):
  119.         anime['rating'] = strip_check(rating.text)
  120.     else:
  121.         anime['rating'] = "0.00"
  122.     #print('Anime rating is: ' + anime['rating'])
  123.  
  124.     # Anime picture
  125.     picture = soup.select_one('meta[property="og:image"]')
  126.     if(hasattr(picture, 'content')):
  127.         anime['picture'] = strip_check(picture['content'].split('/')[-1])
  128.     else:
  129.         anime['picture'] = "No picture"
  130.     #print('Anime picture is: ' + anime['picture'])
  131.  
  132.     # Anime categories
  133.     categories_list = soup.select('div.animetags span.tagname')
  134.     for category in categories_list:
  135.         anime['categories'] += strip_check(category.text) + '|'
  136.     if anime['categories'].endswith('|'):
  137.         anime['categories'] = anime['categories'][:-1]
  138.     #print('Anime categories is|are: ' + anime['categories'])
  139.  
  140.     # Anime characters
  141.     characters_list = soup.select('div[itemprop="character"] span[itemprop="name"]')
  142.     for character in characters_list:
  143.         anime['characters'] += strip_check(character.text) + '|'
  144.     if anime['characters'].endswith('|'):
  145.         anime['characters'] = anime['characters'][:-1]
  146.     #print('Anime characters is|are: ' + anime['characters'])
  147.  
  148.     # Anime epnos
  149.     epnos_list = soup.select('tr[itemprop="episode"] abbr[itemprop="episodeNumber"]')
  150.     for epnos in epnos_list:
  151.         anime['epnos'] += strip_check(epnos.text) + '|'
  152.     if anime['epnos'].endswith('|'):
  153.         anime['epnos'] = anime['epnos'][:-1]
  154.     #print('Anime epnos is|are: ' + anime['epnos'])
  155.  
  156.     # Anime airdates
  157.     airdates_list = soup.select('tr[itemprop="episode"] td[itemprop="datePublished"]')
  158.     for airdate in airdates_list:
  159.         anime['airdates'] += strip_check(airdate['content']) + '|'
  160.     if anime['airdates'].endswith('|'):
  161.         anime['airdates'] = anime['airdates'][:-1]
  162.     #print('Anime airdates is|are: ' + anime['airdates'])
  163.  
  164.     # Anime episodetitles
  165.     episodetitles_list = soup.select('tr[itemprop="episode"] label[itemprop="name"]')
  166.     for episodetitle in episodetitles_list:
  167.         anime['episodetitles'] += strip_check(episodetitle.text) + '|'
  168.     if anime['episodetitles'].endswith('|'):
  169.         anime['episodetitles'] = anime['episodetitles'][:-1]
  170.     #print('Anime episodetitles is|are: ' + anime['episodetitles'])
  171.    
  172.     return anime
  173.  
  174. def escape_string(value):
  175.     return sqlite3.Connection('').execute('SELECT quote(?)', (value,)).fetchone()[0]
  176.  
  177.  
  178. #for file_path in html_files:
  179. #    needed_data.append(fetch_records(file_path))
  180.    
  181. def process_files_concurrently(html_files, max_workers):
  182.     needed_data = []
  183.     with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  184.         future_to_file = {executor.submit(fetch_records, file_path): file_path for file_path in html_files}
  185.         for future in concurrent.futures.as_completed(future_to_file):
  186.             file_path = future_to_file[future]
  187.             try:
  188.                 data = future.result()
  189.                 needed_data.append(data)
  190.             except Exception as exc:
  191.                 print(f'{file_path} generated an exception: {exc}')
  192.     return needed_data
  193.  
  194. max_workers = 50  # Number of files to process concurrently
  195. needed_data = process_files_concurrently(html_files, max_workers)
  196.  
  197. with open('anidb_dump.sql', 'w', encoding='utf-8') as file:
  198.     for anime in needed_data:
  199.         columns = ', '.join(anime.keys())
  200.         values = ', '.join(escape_string(value) if isinstance(value, str) else str(value) for value in anime.values())
  201.         sql = f'INSERT INTO anidb ({columns}) VALUES ({values});\n'
  202.         file.write(sql)
  203.  
  204.  
  205. print('SQL file generated')
Tags: Scraping anidb
Advertisement
Add Comment
Please, Sign In to add comment