chuwanghui 8 gadi atpakaļ
revīzija
07c9d2ac76

+ 1 - 0
ApiCrawler/.idea/.name

@@ -0,0 +1 @@
+ApiCrawler

+ 8 - 0
ApiCrawler/.idea/ApiCrawler.iml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 4 - 0
ApiCrawler/.idea/encodings.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
+</project>

+ 13 - 0
ApiCrawler/.idea/inspectionProfiles/Project_Default.xml

@@ -0,0 +1,13 @@
+<component name="InspectionProjectProfileManager">
+  <profile version="1.0" is_locked="false">
+    <option name="myName" value="Project Default" />
+    <option name="myLocal" value="false" />
+    <inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
+      <option name="ignoredErrors">
+        <list>
+          <option value="E128" />
+        </list>
+      </option>
+    </inspection_tool>
+  </profile>
+</component>

+ 7 - 0
ApiCrawler/.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,7 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="PROJECT_PROFILE" value="Project Default" />
+    <option name="USE_PROJECT_PROFILE" value="true" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 4 - 0
ApiCrawler/.idea/misc.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.14 (C:\Python27\python.exe)" project-jdk-type="Python SDK" />
+</project>

+ 8 - 0
ApiCrawler/.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/ApiCrawler.iml" filepath="$PROJECT_DIR$/.idea/ApiCrawler.iml" />
+    </modules>
+  </component>
+</project>

+ 5 - 0
ApiCrawler/.idea/scopes/scope_settings.xml

@@ -0,0 +1,5 @@
+<component name="DependencyValidationManager">
+  <state>
+    <option name="SKIP_IMPORT_STATEMENTS" value="false" />
+  </state>
+</component>

+ 7 - 0
ApiCrawler/.idea/vcs.xml

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1001 - 0
ApiCrawler/.idea/workspace.xml


+ 0 - 0
ApiCrawler/ApiCrawler/__init__.py


BIN
ApiCrawler/ApiCrawler/__init__.pyc


+ 3 - 0
ApiCrawler/ApiCrawler/begin.py

@@ -0,0 +1,3 @@
+__author__ = 'Administrator'
+from scrapy import cmdline
+cmdline.execute("scrapy crawl api".split())

+ 18 - 0
ApiCrawler/ApiCrawler/items.py

@@ -0,0 +1,18 @@
+# -*- 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 ApiItem(scrapy.Item):
+    # define the fields for your item here like:
+     title = scrapy.Field()
+     url=scrapy.Field()
+     keywords=scrapy.Field()
+     description=scrapy.Field()
+     content=scrapy.Field()
+     #pass

BIN
ApiCrawler/ApiCrawler/items.pyc


+ 103 - 0
ApiCrawler/ApiCrawler/middlewares.py

@@ -0,0 +1,103 @@
+# -*- 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
+
+
+class ApicrawlerSpiderMiddleware(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 ApicrawlerDownloaderMiddleware(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)

+ 58 - 0
ApiCrawler/ApiCrawler/pipelines.py

@@ -0,0 +1,58 @@
+# -*- 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
+
+#引入twisted框架
+from twisted.enterprise import adbapi
+#引入scrapy的日志文件
+from scrapy import log
+#引用数据库驱动
+import MySQLdb
+#引用数据库游标
+import MySQLdb.cursors
+
+class MySQLPipeLine(object):
+    def __init__(self):
+         #其他参数均为字符串,port居然用整形。
+         self.dbpool = adbapi.ConnectionPool('MySQLdb', db='US_Crawler',user='root',host='10.20.5.88', passwd='usestudio-1',port=14062, cursorclass=MySQLdb.cursors.DictCursor,charset='utf8', use_unicode=True)
+    def process_item(self,item,spider):
+        #twisted架构固定写法
+        query=self.dbpool.runInteraction(self._conditional_insert,item)
+        query.addErrback(self.handle_error)
+        return  item
+    def _conditional_insert(self,conn,item):
+        #调用存储过程方法
+        conn.execute('CALL InsertAPIData(%s,%s,%s,%s,%s)', (item['url'],item['title'],item['keywords'],item['description'],item['content']))
+        #log.msg("Item data in db:%s" %item,level=log.DEBUG)
+    def handle_error(self,e):
+        #错误处理
+        log.err(e)
+
+
+#  使用DBUtils连接数据库的方法,比twisted简单很多。
+"""
+import MySQLdb
+from DBUtils.PooledDB import PooledDB
+
+class MySQLPipeLine(object):
+    def __init__(self):
+        self.pool = PooledDB(MySQLdb,5,host='10.20.5.88',user='root',passwd='usestudio-1',db='US_Crawler',port=14062,charset="utf8")
+
+    def process_item(self, item, spider):
+        conn = self.pool.connection()
+        cur = conn.cursor()
+        # 调用存储过程示例
+        #cur.callproc('InsertAPIData', ('1000','张三'))
+        # 存储过程传递参数
+        cur.callproc('InsertAPIData', (item['name'],item['name']))
+        cur.close()
+        conn.commit()
+        conn.close()
+"""
+
+class ApiPipeline(object):
+    def process_item(self, item, spider):
+        return item

BIN
ApiCrawler/ApiCrawler/pipelines.pyc


+ 90 - 0
ApiCrawler/ApiCrawler/settings.py

@@ -0,0 +1,90 @@
+# -*- coding: utf-8 -*-
+
+# Scrapy settings for ApiCrawler 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 = 'ApiCrawler'
+
+SPIDER_MODULES = ['ApiCrawler.spiders']
+NEWSPIDER_MODULE = 'ApiCrawler.spiders'
+
+
+# Crawl responsibly by identifying yourself (and your website) on the user-agent
+#USER_AGENT = 'ApiCrawler (+http://www.yourdomain.com)'
+
+# Obey robots.txt rules
+ROBOTSTXT_OBEY = True
+
+# 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 = {
+#    'ApiCrawler.middlewares.ApicrawlerSpiderMiddleware': 543,
+#}
+
+# Enable or disable downloader middlewares
+# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
+#DOWNLOADER_MIDDLEWARES = {
+#    'ApiCrawler.middlewares.ApicrawlerDownloaderMiddleware': 543,
+#}
+
+# 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 = {
+    'ApiCrawler.pipelines.MySQLPipeLine': 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'

BIN
ApiCrawler/ApiCrawler/settings.pyc


+ 4 - 0
ApiCrawler/ApiCrawler/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.

BIN
ApiCrawler/ApiCrawler/spiders/__init__.pyc


+ 78 - 0
ApiCrawler/ApiCrawler/spiders/apispider.py

@@ -0,0 +1,78 @@
+#-*-coding:utf-8-*-
+#支持中文必须加上上面一句话
+__author__ = 'Administrator'
+import scrapy
+#正则表达式模块
+import re
+
+#包含scrapy中的Request请求,在yield request中用到
+from scrapy.http import Request
+#引入将要保存到数据库的类名称
+from ApiCrawler.items import ApiItem
+
+
+class ApiSpider(scrapy.spiders.Spider):
+    name = "api"
+    #只爬api.1473.cn网址
+    allowed_domains=["api.1473.cn"]
+    #开始爬的网址
+    start_urls=[
+        "http://api.1473.cn"
+    ]
+    #目的是去除重复的url。
+    URLS=[]
+    #计数,一共爬了多少次
+    count=0
+    def parse(self, response):
+        #allUrl=response.url
+        #print allUrl
+
+        #从response中获取内容,保存到数据库,为什么能保存到数据库呢?应该是架构写好的。
+        #extract方法返回unicode字符串
+        apiItem=ApiItem()
+        apiItem['url'] = response.url
+        # normalize-space  解决xpath取出的title值有很多回车空格的问题
+        #text()函数获取标签下面的文本
+        _titles=response.xpath(' normalize-space(/html/head/title/text())')
+        if _titles:
+            apiItem['title'] =_titles[0].extract()
+        else:
+            apiItem['title'] =""
+        #获取meta中的content比较麻烦,国内居然没有资料。
+        _keywords=response.xpath("//meta[@name='keywords']/@content")
+        if _keywords:
+            apiItem['keywords'] = _keywords[0].extract()
+        else:
+            apiItem['keywords'] = ""
+        _description=response.xpath("//meta[@name='description']/@content")
+        if _description:
+            apiItem['description'] = _description[0].extract()
+        else:
+            apiItem['description']=""
+        #首先获取body标签,然后再获取body标签中的所有字符串,为节约代码,下面使用三元操作符号,不熟悉的学生去学习一下三元
+        #python的三元比较奇葩,估计是不入流程序员写的,h = "变量1" if a>b else "变量2"
+        #_content=response.xpath('/html/body').xpath('string(.)').extract()[0];
+        _content=response.xpath('/html/body').xpath('string(.)')
+        #_content=response.xpath("//div[@class='book']").xpath('string(.)')
+        apiItem['content']=_content[0].extract() if _content else ""
+
+        yield apiItem
+
+        # 下面的正则会提取页面中所有的后缀名为.aspx,.html .htm的超级链接,然后循环递归
+        pattern=re.compile(r'((((https|http):\/\/)|\/)[0-9a-zA-Z\/\.@-_%]*?\.(aspx|html|htm))')
+        urls=pattern.findall(response.text)
+        for url in urls:
+
+            #去除重复
+            findUrl=url[0]
+            if findUrl in self.URLS:
+                continue
+            else:
+                self.URLS.append(findUrl)
+            #Request对象需要包含from scrapy.http import Request
+            #递归获取
+            yield Request(findUrl,callback=self.parse)
+
+        #filename=response.url.split("/")[2]
+        #with open(filename,'wb') as f:
+        #    f.writable(response.body)

BIN
ApiCrawler/ApiCrawler/spiders/apispider.pyc


+ 11 - 0
ApiCrawler/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 = ApiCrawler.settings
+
+[deploy]
+#url = http://localhost:6800/
+project = ApiCrawler