From abbcc28c460d7417b45b4d02b624528e7b7bd53a Mon Sep 17 00:00:00 2001 From: jyhl Date: Wed, 6 May 2020 17:16:49 +0800 Subject: [PATCH] init --- README.md | 19 +++++ requirements.dev.txt | 2 + requirements.txt | 26 ++++++ run.bat | 1 + run.sh | 2 + scrapy.cfg | 11 +++ tutorial/__init__.py | 0 tutorial/items.py | 14 ++++ tutorial/middlewares.py | 144 ++++++++++++++++++++++++++++++++ tutorial/pipelines.py | 11 +++ tutorial/settings.py | 92 ++++++++++++++++++++ tutorial/spiders/__init__.py | 4 + tutorial/spiders/demo_spider.py | 18 ++++ useragents.txt | 6 ++ 14 files changed, 350 insertions(+) create mode 100644 README.md create mode 100644 requirements.dev.txt create mode 100644 requirements.txt create mode 100644 run.bat create mode 100755 run.sh create mode 100644 scrapy.cfg create mode 100644 tutorial/__init__.py create mode 100644 tutorial/items.py create mode 100644 tutorial/middlewares.py create mode 100644 tutorial/pipelines.py create mode 100644 tutorial/settings.py create mode 100644 tutorial/spiders/__init__.py create mode 100644 tutorial/spiders/demo_spider.py create mode 100644 useragents.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000..7fe1328 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +## 安装pip +``` + pip install -r requirements.txt +``` + +## 配置 tutorial/middlewares.py +``` + # 代理服务器 (配置上对应信息) + proxyHost = "t.16yun.cn" + proxyPort = "31111" + + # 代理隧道验证信息 + proxyUser = "username" + proxyPass = "password" +``` +## +``` + ./run.sh +``` diff --git a/requirements.dev.txt b/requirements.dev.txt new file mode 100644 index 0000000..8ec6f86 --- /dev/null +++ b/requirements.dev.txt @@ -0,0 +1,2 @@ +scrapy +scrapy-random-useragent diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e0357d0 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,26 @@ +attrs==19.3.0 +Automat==20.2.0 +cffi==1.14.0 +constantly==15.1.0 +cryptography==2.9.2 +cssselect==1.1.0 +hyperlink==19.0.0 +idna==2.9 +incremental==17.5.0 +lxml==4.5.0 +parsel==1.5.2 +Protego==0.1.16 +pyasn1==0.4.8 +pyasn1-modules==0.2.8 +pycparser==2.20 +PyDispatcher==2.0.5 +PyHamcrest==2.0.2 +pyOpenSSL==19.1.0 +queuelib==1.5.0 +Scrapy==2.1.0 +scrapy-random-useragent==0.2 +service-identity==18.1.0 +six==1.14.0 +Twisted==20.3.0 +w3lib==1.21.0 +zope.interface==5.1.0 diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..ca2cc5d --- /dev/null +++ b/run.bat @@ -0,0 +1 @@ +scrapy crawl demo diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..c582b4b --- /dev/null +++ b/run.sh @@ -0,0 +1,2 @@ +#!/bin/bash +scrapy crawl demo diff --git a/scrapy.cfg b/scrapy.cfg new file mode 100644 index 0000000..d79f6f1 --- /dev/null +++ b/scrapy.cfg @@ -0,0 +1,11 @@ +# Automatically created by: scrapy startproject +# +# For more information about the [deploy] section see: +# https://scrapyd.readthedocs.io/en/latest/deploy.html + +[settings] +default = tutorial.settings + +[deploy] +#url = http://localhost:6800/ +project = tutorial diff --git a/tutorial/__init__.py b/tutorial/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tutorial/items.py b/tutorial/items.py new file mode 100644 index 0000000..569bb16 --- /dev/null +++ b/tutorial/items.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your scraped items +# +# See documentation in: +# https://doc.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class TutorialItem(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git a/tutorial/middlewares.py b/tutorial/middlewares.py new file mode 100644 index 0000000..d73385b --- /dev/null +++ b/tutorial/middlewares.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your spider middleware +# +# See documentation in: +# https://doc.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + +# ! -*- encoding:utf-8 -*- +import base64 +import sys +import random + +PY3 = sys.version_info[0] >= 3 + + +def base64ify(bytes_or_str): + if PY3 and isinstance(bytes_or_str, str): + input_bytes = bytes_or_str.encode('utf8') + else: + input_bytes = bytes_or_str + + output_bytes = base64.urlsafe_b64encode(input_bytes) + if PY3: + return output_bytes.decode('ascii') + else: + return output_bytes + + +class ProxyMiddleware(object): + def process_request(self, request, spider): + # 代理服务器 + proxyHost = "n10.t.16yun.cn" + proxyPort = "31111" + + # 代理隧道验证信息 + proxyUser = "username" + proxyPass = "password" + + request.meta['proxy'] = "http://{0}:{1}".format(proxyHost, proxyPort) + + # 添加验证头 + encoded_user_pass = base64ify(proxyUser + ":" + proxyPass) + request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass + + # 设置IP切换头(根据需求) + tunnel = random.randint(1, 10000) + request.headers['Proxy-Tunnel'] = str(tunnel) + + +class TutorialSpiderMiddleware(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. + + # 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. + + # 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 doesn’t have a response associated. + + # 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 TutorialDownloaderMiddleware(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) diff --git a/tutorial/pipelines.py b/tutorial/pipelines.py new file mode 100644 index 0000000..65c1937 --- /dev/null +++ b/tutorial/pipelines.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +# Define your item pipelines here +# +# Don't forget to add your pipeline to the ITEM_PIPELINES setting +# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html + + +class TutorialPipeline(object): + def process_item(self, item, spider): + return item diff --git a/tutorial/settings.py b/tutorial/settings.py new file mode 100644 index 0000000..1a0f132 --- /dev/null +++ b/tutorial/settings.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- + +# Scrapy settings for tutorial project +# +# For simplicity, this file contains only settings considered important or +# commonly used. You can find more settings consulting the documentation: +# +# https://doc.scrapy.org/en/latest/topics/settings.html +# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html +# https://doc.scrapy.org/en/latest/topics/spider-middleware.html + +BOT_NAME = 'tutorial' + +SPIDER_MODULES = ['tutorial.spiders'] +NEWSPIDER_MODULE = 'tutorial.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'tutorial (+http://www.yourdomain.com)' + +# Obey robots.txt rules +ROBOTSTXT_OBEY = True + +DUPEFILTER_CLASS = 'scrapy.dupefilters.BaseDupeFilter' +# Configure maximum concurrent requests performed by Scrapy (default: 16) +#CONCURRENT_REQUESTS = 32 + +# Configure a delay for requests for the same website (default: 0) +# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay +# See also autothrottle settings and docs +#DOWNLOAD_DELAY = 3 +# The download delay setting will honor only one of: +#CONCURRENT_REQUESTS_PER_DOMAIN = 16 +#CONCURRENT_REQUESTS_PER_IP = 16 + +# Disable cookies (enabled by default) +#COOKIES_ENABLED = False + +# Disable Telnet Console (enabled by default) +#TELNETCONSOLE_ENABLED = False + +# Override the default request headers: +#DEFAULT_REQUEST_HEADERS = { +# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', +# 'Accept-Language': 'en', +#} + +# Enable or disable spider middlewares +# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html +#SPIDER_MIDDLEWARES = { +# 'tutorial.middlewares.TutorialSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html +DOWNLOADER_MIDDLEWARES = { + 'tutorial.middlewares.ProxyMiddleware': 100, + 'random_useragent.RandomUserAgentMiddleware': 400 +} +USER_AGENT_LIST = "useragents.txt" +# Enable or disable extensions +# See https://doc.scrapy.org/en/latest/topics/extensions.html +#EXTENSIONS = { +# 'scrapy.extensions.telnet.TelnetConsole': None, +#} + +# Configure item pipelines +# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html +#ITEM_PIPELINES = { +# 'tutorial.pipelines.TutorialPipeline': 300, +#} + +# Enable and configure the AutoThrottle extension (disabled by default) +# See https://doc.scrapy.org/en/latest/topics/autothrottle.html +#AUTOTHROTTLE_ENABLED = True +# The initial download delay +#AUTOTHROTTLE_START_DELAY = 5 +# The maximum download delay to be set in case of high latencies +#AUTOTHROTTLE_MAX_DELAY = 60 +# The average number of requests Scrapy should be sending in parallel to +# each remote server +#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 +# Enable showing throttling stats for every response received: +#AUTOTHROTTLE_DEBUG = False + +# Enable and configure HTTP caching (disabled by default) +# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings +#HTTPCACHE_ENABLED = True +#HTTPCACHE_EXPIRATION_SECS = 0 +#HTTPCACHE_DIR = 'httpcache' +#HTTPCACHE_IGNORE_HTTP_CODES = [] +#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' diff --git a/tutorial/spiders/__init__.py b/tutorial/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/tutorial/spiders/__init__.py @@ -0,0 +1,4 @@ +# This package will contain the spiders of your Scrapy project +# +# Please refer to the documentation for information on how to create and manage +# your spiders. diff --git a/tutorial/spiders/demo_spider.py b/tutorial/spiders/demo_spider.py new file mode 100644 index 0000000..384d62d --- /dev/null +++ b/tutorial/spiders/demo_spider.py @@ -0,0 +1,18 @@ +import scrapy + + +class DemoSpider(scrapy.Spider): + name = "demo" + + + def start_requests(self): + urls = [ + 'http://httpbin.org/ip', + 'http://httpbin.org/ip', + 'http://httpbin.org/headers', + ] + for url in urls: + yield scrapy.Request(url=url, callback=self.parse) + + def parse(self, response): + self.log('{}'.format(response.body)) diff --git a/useragents.txt b/useragents.txt new file mode 100644 index 0000000..74161f0 --- /dev/null +++ b/useragents.txt @@ -0,0 +1,6 @@ +Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/40 +Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; QQBrowser/8.3.4769.400) +MozillaTest/5.0 (compatible; YodaoBot/1.0; http://www.yodao.com/help/webmaster/spider/; ) +Mozilla/5.0 (Windows NT 6.2; rv:39.0) Gecko/20100101 Firefox/39.0 +Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; QQBrowser/8.3.4769.400) +Mozilla/5.0 (Windows NT 6.1; rv:39.0) Gecko/20100101 Firefox/39.0