-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIdolSankakuParser.py
More file actions
200 lines (157 loc) · 6.68 KB
/
IdolSankakuParser.py
File metadata and controls
200 lines (157 loc) · 6.68 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from SankakuParserBase import SankakuParserBase
from urllib.parse import quote_plus
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 requests
import json
import re
from bs4 import BeautifulSoup
class IdolSankakuParser(SankakuParserBase):
def __init__(self):
super().__init__()
self.search_params = "auto_page=t&page=1"
self.last_next_id = ""
self.last_search_tags = ""
def check_auth(self, user=None, delay=30):
driver = super()._get_driver()
driver.get("https://idol.sankakucomplex.com/home")
present = EC.presence_of_element_located((By.CSS_SELECTOR, f"#user-index"))
WebDriverWait(driver, delay).until(present)
user_img = driver.find_elements(By.CSS_SELECTOR, f"#user-index .user-home-heading img")
if not user_img:
return False
if user:
title = user_img[0].get_attribute('title')
if title != user:
self._clear_all_site_data()
return False
return True
def auth(self, user, password, delay=30):
driver = super()._get_driver()
try:
driver.get("https://idol.sankakucomplex.com/users/login")
present = EC.presence_of_element_located((By.CSS_SELECTOR, "form input[name='user[name]']"))
WebDriverWait(driver, delay).until(present)
time.sleep(3)
email_input = driver.find_element(By.CSS_SELECTOR, "form input[name='user[name]']")
password_input = driver.find_element(By.CSS_SELECTOR, "form input[name='user[password]']")
submit_button = driver.find_element(By.CSS_SELECTOR, "form input[type='submit']")
email_input.send_keys(user)
password_input.send_keys(password)
submit_button.click()
present = EC.presence_of_element_located((By.CSS_SELECTOR, f"#user-index img[title='{user}']"))
WebDriverWait(driver, delay).until(present)
except Exception as e:
raise Exception('Wrong username or password')
time.sleep(1)
def search(self, tags):
self.last_search_tags = quote_plus(tags)
data = self._get_html(f'https://idol.sankakucomplex.com/posts?{self.search_params}&tags={self.last_search_tags}')
return self._search_cleaner(data)
def auto_tag(self, text):
try:
words = text.strip().split()
last_word = words[0] if words else ""
if last_word == "":
return []
encoded_tag = quote_plus(last_word)
data = self._get_html(f'https://idol.sankakucomplex.com/tags/autosuggest?tag={encoded_tag}&version=1&type=posts', with_driver=False)
soup = BeautifulSoup(data, 'html.parser')
tags = []
for li in soup.find_all('li', class_='ui-menu-item'):
tag_value = li.get('data-autocomplete-value')
if tag_value:
tags.append(tag_value)
return tags
except Exception as e:
return []
def next(self):
if self.last_next_id is None:
return []
data = self._get_html(f'https://idol.sankakucomplex.com/posts?{self.search_params}&tags={self.last_search_tags}&next={self.last_next_id}')
return self._search_cleaner(data)
def get_full_info(self, media):
data = self._get_html(f'https://idol.sankakucomplex.com/posts/{media["id"]}')
soup = BeautifulSoup(data, 'html.parser')
# Find media link
media_link = soup.find('a', id='image-link')
if media_link:
# Image case
href = media_link.get('href')
if not href:
raise ValueError("Media link has no href attribute")
if href.startswith('//'):
media_url = 'https:' + href
else:
media_url = href
else:
video = soup.find('video', id='image')
if video:
# Video case
src = video.get('src')
if not src:
raise ValueError("Video has no src attribute")
if src.startswith('//'):
media_url = 'https:' + src
else:
media_url = src
else:
raise ValueError("No media (image or video) found")
# Extract file extension from URL
file_name = media_url.split('?')[0].split('/')[-1]
if '.' not in file_name:
raise ValueError("Cannot determine file format from URL")
file_format = file_name.split('.')[-1].lower()
# Find tags
tag_links = soup.find_all('a', class_='tag-link')
if not tag_links:
raise ValueError("No tag links found")
tags = []
for link in tag_links:
tag_name = link.get_text(strip=True)
if tag_name:
tags.append(tag_name)
tags = list(dict.fromkeys(tags))
return {
'id': media['id'],
'file': media_url,
'format': file_format,
'tags': super()._tags_cleaner(tags),
'request_full_info': False
}
def _get_html(self, url, with_driver=True):
if with_driver:
session = self._get_requests_session()
response = session.get(url)
session.close()
return response.text
else:
return requests.get(url).text
def _search_cleaner(self, data):
soup = BeautifulSoup(data, 'html.parser')
next_page_div = soup.find('div', attrs={'next-page-url': True})
if next_page_div:
next_page_url = next_page_div.get('next-page-url')
match = re.search(r'next=([^&]+)', next_page_url)
if match:
self.last_next_id = match.group(1)
else:
self.last_next_id = None
clean_data = []
scripts = soup.find_all('script', string=re.compile(r'Post\.register'))
for script in scripts:
script_content = script.string
match = re.search(r'Post\.register\((.*?)\);', script_content, re.DOTALL)
if match:
try:
post_data = json.loads(match.group(1))
if 'id' in post_data:
clean_data.append({
'id': post_data['id'],
'request_full_info': True
})
except json.JSONDecodeError:
continue
return clean_data