]> git.lizzy.rs Git - nhentai.git/blob - nhentai/parser.py
use format
[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 import constant
8 from logger import logger
9 from tabulate import tabulate
10
11
12 def request(method, url, **kwargs):
13     if not hasattr(requests, method):
14         raise AttributeError('\'requests\' object has no attribute \'{}\''.format(method))
15
16     return requests.__dict__[method](url, proxies=constant.PROXY, **kwargs)
17
18
19 def doujinshi_parser(id_):
20     if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
21         raise Exception('Doujinshi id({}) is not valid'.format(id_))
22
23     id_ = int(id_)
24     logger.log(15, 'Fetching doujinshi information of id {}'.format(id_))
25     doujinshi = dict()
26     doujinshi['id'] = id_
27     url = '{}/{}/'.format(constant.DETAIL_URL, id_)
28
29     try:
30         response = request('get', url).content
31     except Exception as e:
32         logger.critical(str(e))
33         sys.exit()
34
35     html = BeautifulSoup(response)
36     doujinshi_info = html.find('div', attrs={'id': 'info'})
37
38     title = doujinshi_info.find('h1').text
39     subtitle = doujinshi_info.find('h2')
40     doujinshi['name'] = title
41     doujinshi['subtitle'] = subtitle.text if subtitle else ''
42
43     doujinshi_cover = html.find('div', attrs={'id': 'cover'})
44     img_id = re.search('/galleries/([\d]+)/cover\.(jpg|png)$', doujinshi_cover.a.img['src'])
45     if not img_id:
46         logger.critical('Tried yo get image id failed')
47         sys.exit()
48     doujinshi['img_id'] = img_id.group(1)
49     doujinshi['ext'] = img_id.group(2)
50
51     pages = 0
52     for _ in doujinshi_info.find_all('div', class_=''):
53         pages = re.search('([\d]+) pages', _.text)
54         if pages:
55             pages = pages.group(1)
56             break
57     doujinshi['pages'] = int(pages)
58     return doujinshi
59
60
61 def search_parser(keyword, page):
62     logger.debug('Searching doujinshis of keyword {}'.format(keyword))
63     result = []
64     try:
65         response = request('get', url=constant.SEARCH_URL, params={'q': keyword, 'page': page}).content
66     except requests.ConnectionError as e:
67         logger.critical(e)
68         logger.warn('If you are in China, please configure the proxy to fu*k GFW.')
69         raise SystemExit
70
71     html = BeautifulSoup(response)
72     doujinshi_search_result = html.find_all('div', attrs={'class': 'gallery'})
73     for doujinshi in doujinshi_search_result:
74         doujinshi_container = doujinshi.find('div', attrs={'class': 'caption'})
75         title = doujinshi_container.text.strip()
76         title = (title[:85] + '..') if len(title) > 85 else title
77         id_ = re.search('/g/(\d+)/', doujinshi.a['href']).group(1)
78         result.append({'id': id_, 'title': title})
79     return result
80
81
82 def print_doujinshi(doujinshi_list):
83     if not doujinshi_list:
84         return
85     doujinshi_list = [i.values() for i in doujinshi_list]
86     headers = ['id', 'doujinshi']
87     logger.info('Search Result\n' +
88                 tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
89
90 if __name__ == '__main__':
91     print(doujinshi_parser("32271"))