forked from chuanweihu/Douban-Scraping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
douban_spiderman.py
334 lines (268 loc) · 12.4 KB
/
douban_spiderman.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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import time
import urllib
from fake_useragent import UserAgent
import requests
from requests_html import HTMLSession
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
import re
from lxml import etree
import numpy as np
import pandas as pd
from requests_toolbelt import threaded
from requests_toolbelt import user_agent
DEFAULT_URL = "https://movie.douban.com/tag/#/?sort=U&range=0,10&tags=电影"
DEFAULT_PAGE = 2000
class DoubanSpiderMan(object):
"""docstring for Crawler
:param start_url: The URL from which the HTML originated
:param locators: The xpath of elements
:param df: The final output of parser
:param timeout: The timeout of crawler
:param result: The temperally output of parser
"""
def __init__(self):
self.locators = {'original_title': '//*[@id="content"]/h1/span[@property="v:itemreviewed"]/text()',
'release_year': '//*[@id="content"]/h1/span[@class="year"]/text()',
'poster_url': '//*[@id="mainpic"]/a/img/@src',
'director': '//*[@id="info"]/span[1]/span[2]/a[@rel="v:directedBy"]/text()',
'writer': '//*[@id="info"]/span[2]/span[@class="attrs"]/a[@*]/text()',
'actor': '//*[@id="info"]/span[@class="actor"]//*[@rel="v:starring"]/text()',
'genre': '//*[@id="info"]/span[@property="v:genre"]/text()',
'region': '//*[@id="info"]/text()',
'language': '//*[@id="info"]/text()',
'release_date': '//*[@id="info"]/span[@property="v:initialReleaseDate"]/text()',
'runtime': '//*[@id="info"]/span[@property="v:runtime"]/text()',
'alternative_title': '//*[@id="info"]/text()',
'imdb_id': '//*[@id="info"]/a[@rel="nofollow"]/text()',
'vote_average': '//*[@id="interest_sectl"]/div/div[2]/strong/text()',
'vote_count': '//*[@id="interest_sectl"]/div/div[2]/div/div[2]/a/span/text()',
'vote_start5_percent': '//*[@id="interest_sectl"]/div/div[3]/div[1]/span[2]/text()',
'vote_start4_percent': '//*[@id="interest_sectl"]/div/div[3]/div[2]/span[2]/text()',
'vote_start3_percent': '//*[@id="interest_sectl"]/div/div[3]/div[3]/span[2]/text()',
'vote_start2_percent': '//*[@id="interest_sectl"]/div/div[3]/div[4]/span[2]/text()',
'vote_start1_percent': '//*[@id="interest_sectl"]/div/div[3]/div[5]/span[2]/text()',
'tag': '//*[@id="content"]/div[@class="grid-16-8 clearfix"]/div[2]/div[@class="tags"]/div/a[@*]/text()',
'watched_count': '//*[@id="subject-others-interests"]/div/a[1]/text()',
'towatch_count': '//*[@id="subject-others-interests"]/div/a[2]/text()',
'overview': '//*[@id="link-report"]//*[@property="v:summary"]/text()',
'recommend_name': '//*[@id="recommendations"]/div/dl[@*]/dd/a/text()',
'recommend_url': '//*[@id="recommendations"]/div/dl[@*]/dd/a/@href',
'short_review': '//*[@id="hot-comments"]/div[@*]/div/p/span/text()',
'short_review_count': '//*[@id="comments-section"]/div[1]/h2/span/a/text()',
'full_review_title': '//*[@class="reviews mod movie-content"]/div[2]/div[@*]/div/div[@class="main-bd"]/h2/a/text()',
'full_review_short': '//*/div[@class="short-content"]/text()',
'full_review_count': '//*[@id="content"]//*[@class="reviews mod movie-content"]/header//*/a[@href="reviews"]/text()',
'full_review_link': '//*[@class="reviews mod movie-content"]/div[2]/div[@*]/div/div[@class="main-bd"]/h2/a/@href',
'discussion_count': '//*[@id="content"]//*/div[@class="section-discussion"]/p/a/text()',
'ask_count': '//*[@id="askmatrix"]//*/span[@class="pl"]/a/text()',
}
self.timeout = 20
self.columns = ['id'] + [val for val in self.locators]
# Add proies by ShawdowSocks (Scraying Out of Great Wall)
self.proxies = {'http': 'http://127.0.0.1:1087',
'https': 'http://127.0.0.1:1087'}
# Add proies by Trojan
#self.proxies = {'http': 'http://127.0.0.1:1081',
# 'https': 'http://127.0.0.1:1081'}
def get_headers(self):
"""
Settings for headers
"""
ua = UserAgent()
user_agent = ua.random
headers = {'user-agent': user_agent}
return headers
def set_chrome_options(self, proxies=False):
"""
Chrome webdriver sets
:chrome_options: add arguments
"""
chrome_options = Options()
# Add proies
if proxies:
options.add_argument('--proxy-server={}'.format(self.proxies['http']))
chrome_options.add_argument('--user-agent={}'.format(
self.get_headers()['user-agent'])
)
chrome_options.add_argument('--disable-gpu')
#chrome_options.add_argument('--headless')
#chrome_options.add_argument('--blink-settings=imagesEnabled=false')
chrome_options.add_argument('--window-size=800,900')
chrome_options.add_experimental_option('excludeSwitches',
['enable-automation'])
return chrome_options
def wait_for_element_located(self, driver, locator, timeout=20):
try:
element = WebDriverWait(driver, timeout).until(
EC.presence_of_element_located((By.CSS_SELECTOR, locator))
)
except:
print('No Such Element There!\n{}'.format('-'*20))
print('locator is {}'.format(locator))
return
else:
return element
def selenium_parser_urls(self, url):
"""
Use selenium to parser
"""
driver = webdriver.Chrome(options=self.set_chrome_options(proxies=False))
driver.implicitly_wait(10)
start_url = url
print('link is %s' %start_url)
print('='*20)
if proxies:
driver.get(start_url, proxies=proxies)
else:
driver.get(start_url)
time.sleep(np.random.randint(10, 15)+np.random.random())
time.sleep(60)
for count in range(DEFAULT_PAGE // 20 - 1):
load_more_locator = 'a.more'
try:
print(f'count {count}: start click\n', '='*20)
continue_element = self.wait_for_element_located(driver,
load_more_locator)
continue_element.click()
print(f'count {count}: after click', '='*20)
except:
print('No more elements to show!')
break
finally:
print('sleeping')
time.sleep(np.random.randint(5, 10)+np.random.random())
html = driver.page_source
root = etree.HTML(html)
movie_chains_xpath = '//*[@id="app"]/div/div[1]/div[3]/a[@*]/@href'
movie_chains = root.xpath(movie_chains_xpath)
driver.close()
print(f"length of movie_chains: {len(movie_chains)}", '\n\t', '-'*20)
return movie_chains
def selenium_parser_page(self, url):
"""
Use selenium to parser
"""
chrome_options = self.set_chrome_options(proxies=False)
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
time.sleep(np.random.randint(1, 5))
try:
html = driver.page_source
except:
print('exceptions!\n', 'scrapying by requests instead!')
try:
return self.requests_html_parser_page(url)
except:
return self.requests_parser_page(url)
else:
root = etree.HTML(html)
s_results = {'id': re.findall(r'.*?subject/(\d+)', url)[0]}
for locator in self.locators:
s_results[locator] = root.xpath(self.locators[locator])
driver.close()
return s_results
def requests_parser_page(self, url):
"""
Use requests to parser
"""
r = requests.get(url, headers=self.get_headers())
time.sleep(np.random.randint(1, 5)+np.random.random())
root = etree.HTML(r.text)
r_results = {'id': re.findall(r'.*?subject/(\d+)', url)[0]}
for locator in self.locators:
r_results[locator] = root.xpath(self.locators[locator])
return r_results
def requests_html_parser_page(self, url):
"""
Use requests-html to parser
"""
if url is None:
return None
else:
session = HTMLSession()
r = session.get(url)
r.html.render(wait=5)
rh_results = {'id': re.findall(r'.*?subject/(\d+)', url)[0]}
for locator in self.locators:
rh_results[locator] = r.html.xpath(self.locators[locator])
return rh_results
def crawl_page(self, url, page_state=True, interactive=False):
"""
Parsing html
:param url: scrapying target
:param page_state: True for static page
:param interactive: True for interactive access
"""
page_lists = []
if url is None:
return None
elif page_state:
print('page crawl is requests_parser_page\n\t', '-'*20)
page_results = self.requests_parser_page(url)
elif not interactive:
print('page crawl is requests_html_parser_page\n\t', '-'*20)
page_results = self.requests_html_parser_page(url)
else:
print('page crawl is selenium_parser_page\n\t', '-'*20)
page_results = self.selenium_parser_page(url)
return page_results
def initialize_session(self, session):
session.headers['User-Agent'] = self.get_headers()['user-agent']
def async_crawl_pages(self, urls):
"""
async parsing htmls
"""
urls_to_get = []
for url in urls:
urls_to_get.append({'url': url,
'method': 'GET',
'headers': self.get_headers(),
'timeout': self.timeout})
responses, errors = threaded.map(urls_to_get,
num_processes=3)
page_lists = []
for response in responses:
print(f'response is {response}')
print('GET {0}. Returned {1}.'.format(response.request_kwargs['url'],
response.status_code))
root = etree.HTML(response.text)
print(f'type(root) is {type(root)}')
r_results = {'id': re.findall(r'.*?subject/(\d+)',
response.request_kwargs['url'])[0]}
for locator in self.locators:
r_results[locator] = root.xpath(self.locators[locator])
page_lists.append(r_results)
df_pages = pd.DataFrame(page_lists, columns=self.columns)
df_pages.info()
return df_pages
def crawl_pages(self, urls):
"""
Parsing htmls
"""
page_lists = []
for idx, url in enumerate(urls):
print(f'{idx} url: \n\t{url}\n\t', '-'*20)
page_lists.append(self.crawl_page(url))
df_pages = pd.DataFrame(page_lists, columns=self.columns)
df_pages.info()
return df_pages
def crawl(self, url=DEFAULT_URL, async_crawl=False):
"""
Crawling
"""
movie_chains = self.selenium_parser_urls(url)
if not async_crawl:
return self.crawl_pages(movie_chains)
else:
return self.async_crawl_pages(movie_chains)
if __name__ == "__main__":
douban_crawler = DoubanSpiderMan()
df = douban_crawler.crawl(async_crawl=True)
df.to_csv('douban_crawler.csv', index=False)