网络爬虫--22.【CrawlSpider实战】实现微信小程序社区爬虫
生活随笔
收集整理的這篇文章主要介紹了
网络爬虫--22.【CrawlSpider实战】实现微信小程序社区爬虫
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一. CrawlSpider
- 二. CrawlSpider案例
- 1. 目錄結構
- 2. wxapp_spider.py
- 3. items.py
- 4. pipelines.py
- 5. settings.py
- 6. start.py
- 三. 重點總結
一. CrawlSpider
現實情況下,我們需要對滿足某個特定條件的url進行爬取,這時候就可以通過CrawlSpider完成。
CrawlSpider繼承自Spider,只不過在之前的基礎上增加了新的功能,可以定義爬取的url規則,Scrapy碰到滿足條件的url都進行爬取,而不用手動的yield Request。
二. CrawlSpider案例
1. 目錄結構
2. wxapp_spider.py
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from wxapp.items import WxappItemclass WxappSpiderSpider(CrawlSpider):name = 'wxapp_spider'allowed_domains = ['wxapp-union.com']start_urls = ['http://www.wxapp-union.com/portal.php?mod=list&catid=1&page=1']rules = (Rule(LinkExtractor(allow=r'.+mod=list&catid=1&page=\d'), follow=True),Rule(LinkExtractor(allow=r'.+article-.+\.html'), callback='parse_detail', follow=False))def parse_detail(self, response):title = response.xpath("//h1[@class='ph']/text()").get()# print(title)author_p = response.xpath(".//p[@class='authors']")author = author_p.xpath("./a/text()").get()pub_time = author_p.xpath("./span/text()").get()# print('author:%s/pub_time:%s'%(author,pub_time))article_content = response.xpath(".//td[@id='article_content']//text()").getall()content = "".join(article_content).strip()# print(content)# print('-'*30)item = WxappItem(title=title,author=author,pub_time=pub_time,content=content)yield item3. items.py
# -*- coding: utf-8 -*-# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass WxappItem(scrapy.Item):# define the fields for your item here like:title = scrapy.Field()author = scrapy.Field()pub_time = scrapy.Field()content = scrapy.Field()4. pipelines.py
# -*- coding: utf-8 -*-# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exporters import JsonLinesItemExporterclass WxappPipeline(object):def __init__(self):self.fp = open('wxjc.json','wb')self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')def process_item(self, item, spider):self.exporter.export_item(item)return itemdef close_spider(self,spider):self.fp.close()5. settings.py
# -*- coding: utf-8 -*-# Scrapy settings for wxapp project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.htmlBOT_NAME = 'wxapp'SPIDER_MODULES = ['wxapp.spiders'] NEWSPIDER_MODULE = 'wxapp.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'wxapp (+http://www.yourdomain.com)'# Obey robots.txt rules ROBOTSTXT_OBEY = False# 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://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 1 # 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','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36' }# Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'wxapp.middlewares.WxappSpiderMiddleware': 543, #}# Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'wxapp.middlewares.WxappDownloaderMiddleware': 543, #}# Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #}# Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = {'wxapp.pipelines.WxappPipeline': 300, }# Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.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://docs.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'6. start.py
from scrapy import cmdlinecmdline.execute("scrapy crawl wxapp_spider".split())三. 重點總結
總結
以上是生活随笔為你收集整理的网络爬虫--22.【CrawlSpider实战】实现微信小程序社区爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络爬虫--20.【Scrapy-Red
- 下一篇: 平板电脑硬件如何测试软件,先锋(Pion