]> git.lizzy.rs Git - nhentai.git/blob - nhentai/parser.py
7585a2950c88198a818dcd0524fb670b43915cf8
[nhentai.git] / nhentai / parser.py
1 # coding: utf-8
2 from __future__ import print_function
3 import sys
4 import re
5 import requests
6 from bs4 import BeautifulSoup
7 from constant import DETAIL_URL, SEARCH_URL
8 from logger import logger
9 from tabulate import tabulate
10
11
12 def doujinshi_parser(id):
13     if not isinstance(id, (int, )) and (isinstance(id, (str, )) and not id.isdigit()):
14         raise Exception('Doujinshi id(%s) is not valid' % str(id))
15     id = int(id)
16     logger.debug('Fetching doujinshi information of id %d' % id)
17     doujinshi = dict()
18     doujinshi['id'] = id
19     url = '%s/%d/' % (DETAIL_URL, id)
20
21     try:
22         response = requests.get(url).content
23     except Exception as e:
24         logger.critical('%s%s' % tuple(e.message))
25         sys.exit()
26
27     html = BeautifulSoup(response)
28     doujinshi_info = html.find('div', attrs={'id': 'info'})
29
30     title = doujinshi_info.find('h1').text
31     subtitle = doujinshi_info.find('h2')
32
33     doujinshi['name'] = title
34     doujinshi['subtitle'] = subtitle.text if subtitle else ''
35
36     doujinshi_cover = html.find('div', attrs={'id': 'cover'})
37     img_id = re.search('/galleries/([\d]+)/cover\.(jpg|png)$', doujinshi_cover.a.img['src'])
38     if not img_id:
39         logger.critical('Tried yo get image id failed')
40         sys.exit()
41     doujinshi['img_id'] = img_id.group(1)
42     doujinshi['ext'] = img_id.group(2)
43
44     pages = 0
45     for _ in doujinshi_info.find_all('div', class_=''):
46         pages = re.search('([\d]+) pages', _.text)
47         if pages:
48             pages = pages.group(1)
49             break
50     doujinshi['pages'] = int(pages)
51     return doujinshi
52
53
54 def search_parser(keyword, page):
55     logger.debug('Searching doujinshis of keyword %s' % keyword)
56     result = []
57     response = requests.get(SEARCH_URL, params={'q': keyword, 'page': page}).content
58     html = BeautifulSoup(response)
59     doujinshi_search_result = html.find_all('div', attrs={'class': 'gallery'})
60     for doujinshi in doujinshi_search_result:
61         doujinshi_container = doujinshi.find('div', attrs={'class': 'caption'})
62         title = doujinshi_container.text.strip()
63         title = (title[:85] + '..') if len(title) > 85 else title
64         id_ = re.search('/g/(\d+)/', doujinshi.a['href']).group(1)
65         result.append({'id': id_, 'title': title})
66     return result
67
68
69 def print_doujinshi(doujinshi_list):
70     if not doujinshi_list:
71         return
72     doujinshi_list = [i.values() for i in doujinshi_list]
73     headers = ['id', 'doujinshi']
74     logger.info('Search Result\n' +
75                 tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
76
77 if __name__ == '__main__':
78     print(doujinshi_parser("32271"))