-
Notifications
You must be signed in to change notification settings - Fork 0
/
SankakuParser.py
173 lines (114 loc) · 5.27 KB
/
SankakuParser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import json
import os
import requests
import shutil
class SankakuParser:
driver = None
search_params = 'lang=en&hide_posts_in_books=in-larger-tags&limit=40'
last_next_id = ""
last_search_tags = ""
def __init__(self, debug_window = False):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--enable-javascript")
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
if not debug_window:
chrome_options.add_argument("--autoplay-policy=user-gesture-required")
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument('headless')
chrome_options.add_argument('window-size=1920x1080')
chrome_options.add_argument("disable-gpu")
chrome_options.add_experimental_option(
"prefs", {"profile.managed_default_content_settings.images": 2}
)
self.driver = webdriver.Chrome(chrome_options=chrome_options)
def __del__(self):
self.driver.quit()
def get_requests_session(self):
session = requests.Session()
selenium_user_agent = self.driver.execute_script('return navigator.userAgent;')
session.headers.update({'user-agent': selenium_user_agent})
for cookie in self.driver.get_cookies():
session.cookies.set(cookie['name'], cookie['value'], domain=cookie['domain'])
access_token = next(
(obj for obj in self.driver.get_cookies() if obj['name'] == 'accessToken'),
None
)
if access_token:
session.headers.update({'Authorization': f"Bearer {access_token['value']}"})
return session
def get_json(self, url):
session = self.get_requests_session()
json_data = session.get(url).json()
if 'success' in json_data and not json_data['success']:
raise Exception(json_data['code'])
return json_data
def auth(self, user, password, delay = 30):
self.driver.get("https://login.sankakucomplex.com/login")
present = EC.presence_of_element_located((By.CSS_SELECTOR, "form input[name='email']"))
WebDriverWait(self.driver, delay).until(present)
time.sleep(3)
email_input = self.driver.find_element(By.CSS_SELECTOR, "form input[name='email']",)
password_input = self.driver.find_element(By.CSS_SELECTOR, "form input[name='password']")
submit_button = self.driver.find_element(By.CSS_SELECTOR, "form button[type='submit']")
email_input.send_keys(user)
password_input.send_keys(password)
submit_button.click()
try:
present = EC.presence_of_element_located((By.CSS_SELECTOR, "input[id='autocomplete']"))
WebDriverWait(self.driver, delay).until(present)
except:
raise Exception('Wrong username or password')
time.sleep(1)
def search(self, tags):
self.last_search_tags = tags.replace(' ', '+')
json = self.get_json(f'https://capi-v2.sankakucomplex.com/posts/keyset?{self.search_params}&tags={self.last_search_tags}')
self.last_next_id = json['meta']['next']
return self.search_cleaner(json)
def next(self):
if self.last_next_id is None:
return []
json = self.get_json(f'https://capi-v2.sankakucomplex.com/posts/keyset?{self.search_params}&tags={self.last_search_tags}&next={self.last_next_id}')
self.last_next_id = json['meta']['next']
return self.search_cleaner(json)
def download(self, json, save_dir, name = None, save_tags = False):
if name is None:
name = json['id']
session = self.get_requests_session()
response = session.get(json['file'], stream=True)
with response as r:
media_file = os.path.join(save_dir, f'{name}.{json["format"]}')
with open(media_file, 'wb') as f:
shutil.copyfileobj(r.raw, f)
session.close()
if save_tags:
tags_file = os.path.join(save_dir, f'{name}.txt')
f = open(tags_file, 'w', encoding="utf-8")
f.write(', '.join(json["tags"]))
f.close()
def search_cleaner(self, json):
clean_data = []
for media in json['data']:
if media['file_url'] is None:
continue
clean_data.append({
'id': media['id'],
'rating': media['rating'],
'preview': media['preview_url'],
'file': media['file_url'],
'type': media['file_type'].split('/')[0],
'format': media['file_type'].split('/')[1],
'width': media['width'],
'height': media['height'],
'size': media['file_size'],
'tags': self.tags_cleaner(media['tags'])
})
return clean_data
def tags_cleaner(self, json):
clean_data = [o['name_en'] for o in json]
return clean_data