bigdata/chapter1/crawler/taobao/middlewares.py

168 lines
5.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
import pdb
import time
import json
import requests
from scrapy.http import HtmlResponse
from selenium.common.exceptions import TimeoutException
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from scrapy_splash import SplashRequest
from scrapy import signals
class ZhihuSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
print('process_spider_input')
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
print('process_spider_output')
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesnt have a response associated.
print('process_start_requests')
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class ZhihuDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class ZhihuChromeMiddleware(object):
CHROME_DRIVER_PATH = r'/Users/guange/.bin/chromedriver'
COOKIES = {
'z_c0': '2|1:0|10:1543151267|4:z_c0|92:Mi4xcFpjMkFBQUFBQUFBWUdnWG5naDZEaWNBQUFDRUFsVk5veXNpWEFELWM4WHU0b3c3anJvR3hobzhvMEpIR004b2xB|aada1968c0f5284002a0bbb552b95af6e87cf3848acc15adfe6d91ed4d9151d8'}
def __init__(self):
options = webdriver.ChromeOptions()
# options.add_argument('--headless')
options.add_argument('--window-size=1366,768')
options.add_argument('--blink-settings=imagesEnabled=false')
SERVICE_ARGS = ['--load-images=false', '--disk-cache=true', '--ignore-ssl-errors=true']
self.driver = webdriver.Chrome(chrome_options=options, service_args=SERVICE_ARGS,
executable_path=self.CHROME_DRIVER_PATH)
self.driver.set_page_load_timeout(30)
self.wait = WebDriverWait(self.driver, 10)
def process_request(self, request, spider):
self.driver.get(request.url)
self.driver.execute_script("scroll(0, 1000);")
time.sleep(1)
rendered_body = self.driver.page_source
return HtmlResponse(request.url, body=rendered_body, encoding="utf-8")
def spider_closed(self, spider, reason):
print('驱动关闭')
self.driver.close()
class RandomProxyMiddleware(object):
_ip_lists = []
def get_ip(self):
if len(self._ip_lists) <= 0:
r = requests.get('http://bigdata1.educoder.net/myapp/api/proxys.json')
self._ip_lists = json.loads(r.text)
data = self._ip_lists.pop()
return "http://%s:%d" % (data['ip'], data['port'])
def process_request(self, request, spider):
if isinstance(request, SplashRequest):
ip = self.get_ip()
print(ip)
request.meta['splash']['args']['proxy'] = ip
# request.meta['proxy'] = ip