標籤:scrapy
這個架構關注了很久,但是直到最近空了才仔細的看了下 這裡我用的是scrapy0.24版本
先來個成品好感受這個架構帶來的便捷性,等這段時間慢慢整理下思緒再把最近學到的關於此架構的知識一一更新到部落格來。
先說明下這個玩具爬蟲的目的
能夠將種子URL頁面當中的小組進行爬取 並分析出有關聯的小組串連 以及小組的組員人數 和組名等資訊
出來的資料大概是這樣的
{ ‘RelativeGroups‘: [u‘http://www.douban.com/group/10127/‘, u‘http://www.douban.com/group/seventy/‘, u‘http://www.douban.com/group/lovemuseum/‘, u‘http://www.douban.com/group/486087/‘, u‘http://www.douban.com/group/lovesh/‘, u‘http://www.douban.com/group/NoAstrology/‘, u‘http://www.douban.com/group/shanghaijianzhi/‘, u‘http://www.douban.com/group/12658/‘, u‘http://www.douban.com/group/shanghaizufang/‘, u‘http://www.douban.com/group/gogo/‘, u‘http://www.douban.com/group/117546/‘, u‘http://www.douban.com/group/159755/‘], ‘groupName‘: u‘\u4e0a\u6d77\u8c46\u74e3‘, ‘groupURL‘: ‘http://www.douban.com/group/Shanghai/‘, ‘totalNumber‘: u‘209957‘}
有啥用 其實這些資料就能夠分析小組與小組之間的關聯度等,如果有心還能抓取到更多的資訊。不在此展開 本文章主要是為了能夠快速感受一把。
首先就是 start 一個新的名為douban的項目
# scrapy startproject douban
# cd douban
這是整個項目的完整後的目錄[email protected]:~/student/py/douban$ tree.├── douban│ ├── __init__.py│ ├── __init__.pyc│ ├── items.py│ ├── items.pyc│ ├── pipelines.py│ ├── pipelines.pyc│ ├── settings.py│ ├── settings.pyc│ └── spiders│ ├── BasicGroupSpider.py│ ├── BasicGroupSpider.pyc│ ├── __init__.py│ └── __init__.pyc├── nohup.out├── scrapy.cfg├── start.sh├── stop.sh└── test.log
編寫實體 items.py , 主要是為了抓回來的資料可以很方便的持久化
[email protected]:~/student/py/douban$ cat douban/items.py# -*- coding: utf-8 -*-# Define here the models for your scraped items## See documentation in:# http://doc.scrapy.org/en/latest/topics/items.htmlfrom scrapy.item import Item, Field class DoubanItem(Item): # define the fields for your item here like: # name = Field() groupName = Field() groupURL = Field() totalNumber = Field() RelativeGroups = Field() ActiveUesrs = Field()
編寫爬蟲並自訂一些規則進行資料的處理
[email protected]:~/student/py/douban$ cat douban/spiders/BasicGroupSpider.py# -*- coding: utf-8 -*-from scrapy.contrib.spiders import CrawlSpider, Rulefrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractorfrom scrapy.selector import HtmlXPathSelectorfrom scrapy.item import Itemfrom douban.items import DoubanItemimport reclass GroupSpider(CrawlSpider): # 爬蟲名 name = "Group" allowed_domains = ["douban.com"] # 種子連結 start_urls = [ "http://www.douban.com/group/explore?tag=%E8%B4%AD%E7%89%A9", "http://www.douban.com/group/explore?tag=%E7%94%9F%E6%B4%BB", "http://www.douban.com/group/explore?tag=%E7%A4%BE%E4%BC%9A", "http://www.douban.com/group/explore?tag=%E8%89%BA%E6%9C%AF", "http://www.douban.com/group/explore?tag=%E5%AD%A6%E6%9C%AF", "http://www.douban.com/group/explore?tag=%E6%83%85%E6%84%9F", "http://www.douban.com/group/explore?tag=%E9%97%B2%E8%81%8A", "http://www.douban.com/group/explore?tag=%E5%85%B4%E8%B6%A3" ] # 規則 滿足後 使用callback指定的函數進行處理 rules = [ Rule(SgmlLinkExtractor(allow=(‘/group/[^/]+/$‘, )),callback=‘parse_group_home_page‘, process_request=‘add_cookie‘), Rule(SgmlLinkExtractor(allow=(‘/group/explore\?tag‘, )), follow=True,process_request=‘add_cookie‘), ] def __get_id_from_group_url(self, url): m = re.search("^http://www.douban.com/group/([^/]+)/$", url) if(m): return m.group(1) else: return 0 def add_cookie(self, request): request.replace(cookies=[ ]); return request; def parse_group_topic_list(self, response): self.log("Fetch group topic list page: %s" % response.url) pass def parse_group_home_page(self, response): self.log("Fetch group home page: %s" % response.url) # 這裡使用的是一個叫 XPath 的選取器 hxs = HtmlXPathSelector(response) item = DoubanItem() #get group name item[‘groupName‘] = hxs.select(‘//h1/text()‘).re("^\s+(.*)\s+$")[0] #get group id item[‘groupURL‘] = response.url groupid = self.__get_id_from_group_url(response.url) #get group members number members_url = "http://www.douban.com/group/%s/members" % groupid members_text = hxs.select(‘//a[contains(@href, "%s")]/text()‘ % members_url).re("\((\d+)\)") item[‘totalNumber‘] = members_text[0] #get relative groups item[‘RelativeGroups‘] = [] groups = hxs.select(‘//div[contains(@class, "group-list-item")]‘) for group in groups: url = group.select(‘div[contains(@class, "title")]/a/@href‘).extract()[0] item[‘RelativeGroups‘].append(url) return item
編寫資料處理的管道這個階段我會把爬蟲收集到的資料存放區到mongodb當中去
[email protected]:~/student/py/douban$ cat douban/pipelines.py# -*- coding: utf-8 -*-# Define your item pipelines here## Don‘t forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport pymongofrom scrapy import logfrom scrapy.conf import settingsfrom scrapy.exceptions import DropItemclass DoubanPipeline(object): def __init__(self): self.server = settings[‘MONGODB_SERVER‘] self.port = settings[‘MONGODB_PORT‘] self.db = settings[‘MONGODB_DB‘] self.col = settings[‘MONGODB_COLLECTION‘] connection = pymongo.Connection(self.server, self.port) db = connection[self.db] self.collection = db[self.col] def process_item(self, item, spider): self.collection.insert(dict(item)) log.msg(‘Item written to MongoDB database %s/%s‘ % (self.db, self.col),level=log.DEBUG, spider=spider) return item
在設定類中設定 所使用的資料處理管道 以及mongodb串連參數 和 user-agent 躲避爬蟲被禁
[email protected]:~/student/py/douban$ cat douban/settings.py# -*- coding: utf-8 -*-# Scrapy settings for douban project## For simplicity, this file contains only the most important settings by# default. All the other settings are documented here:## http://doc.scrapy.org/en/latest/topics/settings.html#BOT_NAME = ‘douban‘SPIDER_MODULES = [‘douban.spiders‘]NEWSPIDER_MODULE = ‘douban.spiders‘# 設定等待時間緩解伺服器壓力 並能夠隱藏自己DOWNLOAD_DELAY = 2RANDOMIZE_DOWNLOAD_DELAY = TrueUSER_AGENT = ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5‘COOKIES_ENABLED = True# 配置使用的資料管道ITEM_PIPELINES = [‘douban.pipelines.DoubanPipeline‘]MONGODB_SERVER=‘localhost‘MONGODB_PORT=27017MONGODB_DB=‘douban‘MONGODB_COLLECTION=‘doubanGroup‘# Crawl responsibly by identifying yourself (and your website) on the user-agent#USER_AGENT = ‘douban (+http://www.yourdomain.com)‘
OK 一個玩具爬蟲就簡單的完成了
啟動啟動命令
nohup scrapy crawl Group --logfile=test.log &
本文出自 “某人說我技術宅” 部落格,請務必保留此出處http://1992mrwang.blog.51cto.com/3265935/1583539
Scrapy 爬蟲執行個體 抓取豆瓣小組資訊並儲存到mongodb中