Spider類定義了如何爬取某個(或某些)網(wǎng)站造成。包括了爬取的動作(例如:是否跟進鏈接)以及如何從網(wǎng)頁的內(nèi)容中提取結(jié)構(gòu)化數(shù)據(jù)(爬取item)局蚀。 換句話說彻桃,Spider就是您定義爬取的動作及分析某個網(wǎng)頁(或者是有些網(wǎng)頁)的地方急但。
class scrapy.Spider是最基本的類澎媒,所有編寫的爬蟲必須繼承這個類。
主要用到的函數(shù)及調(diào)用順序為:
init() : 初始化爬蟲名字和start_urls列表
start_requests() 調(diào)用make_requests_from url():生成Requests對象交給Scrapy下載并返回response
parse() : 解析response波桩,并返回Item或Requests(需指定回調(diào)函數(shù))戒努。Item傳給Item pipline持久化 , 而Requests交由Scrapy下載镐躲,并由指定的回調(diào)函數(shù)處理(默認parse())储玫,一直進行循環(huán),直到處理完所有的數(shù)據(jù)為止匀油。
源碼參考
#所有爬蟲的基類缘缚,用戶定義的爬蟲必須從這個類繼承
class Spider(object_ref):
#定義spider名字的字符串(string)。spider的名字定義了Scrapy如何定位(并初始化)spider敌蚜,所以其必須是唯一的桥滨。
#name是spider最重要的屬性,而且是必須的。
#一般做法是以該網(wǎng)站(domain)(加或不加 后綴 )來命名spider齐媒。 例如蒲每,如果spider爬取 mywebsite.com ,該spider通常會被命名為 mywebsite
name = None
#初始化喻括,提取爬蟲名字邀杏,start_ruls
def __init__(self, name=None, **kwargs):
if name is not None:
self.name = name
# 如果爬蟲沒有名字,中斷后續(xù)操作則報錯
elif not getattr(self, 'name', None):
raise ValueError("%s must have a name" % type(self).__name__)
# python 對象或類型通過內(nèi)置成員__dict__來存儲成員信息
self.__dict__.update(kwargs)
#URL列表唬血。當(dāng)沒有指定的URL時望蜡,spider將從該列表中開始進行爬取。 因此拷恨,第一個被獲取到的頁面的URL將是該列表之一脖律。 后續(xù)的URL將會從獲取到的數(shù)據(jù)中提取。
if not hasattr(self, 'start_urls'):
self.start_urls = []
# 打印Scrapy執(zhí)行后的log信息
def log(self, message, level=log.DEBUG, **kw):
log.msg(message, spider=self, level=level, **kw)
# 判斷對象object的屬性是否存在腕侄,不存在做斷言處理
def set_crawler(self, crawler):
assert not hasattr(self, '_crawler'), "Spider already bounded to %s" % crawler
self._crawler = crawler
@property
def crawler(self):
assert hasattr(self, '_crawler'), "Spider not bounded to any crawler"
return self._crawler
@property
def settings(self):
return self.crawler.settings
#該方法將讀取start_urls內(nèi)的地址小泉,并為每一個地址生成一個Request對象,交給Scrapy下載并返回Response
#該方法僅調(diào)用一次
def start_requests(self):
for url in self.start_urls:
yield self.make_requests_from_url(url)
#start_requests()中調(diào)用冕杠,實際生成Request的函數(shù)微姊。
#Request對象默認的回調(diào)函數(shù)為parse(),提交的方式為get
def make_requests_from_url(self, url):
return Request(url, dont_filter=True)
#默認的Request對象回調(diào)函數(shù)分预,處理返回的response兢交。
#生成Item或者Request對象。用戶必須實現(xiàn)這個類
def parse(self, response):
raise NotImplementedError
@classmethod
def handles_request(cls, request):
return url_is_from_spider(request.url, cls)
def __str__(self):
return "<%s %r at 0x%0x>" % (type(self).__name__, self.name, id(self))
__repr__ = __str__
主要屬性和方法
-
name
定義spider名字的字符串噪舀。
例如魁淳,如果spider爬取 mywebsite.com ,該spider通常會被命名為 mywebsite
-
allowed_domains
包含了spider允許爬取的域名(domain)的列表与倡,可選界逛。
-
start_urls
初始URL元祖/列表。當(dāng)沒有制定特定的URL時纺座,spider將從該列表中開始進行爬取息拜。
-
start_requests(self)
該方法必須返回一個可迭代對象(iterable)。該對象包含了spider用于爬染幌臁(默認實現(xiàn)是使用 start_urls 的url)的第一個Request少欺。
當(dāng)spider啟動爬取并且未指定start_urls時,該方法被調(diào)用馋贤。
-
parse(self, response)
當(dāng)請求url返回網(wǎng)頁沒有指定回調(diào)函數(shù)時赞别,默認的Request對象回調(diào)函數(shù)。用來處理網(wǎng)頁返回的response配乓,以及生成Item或者Request對象仿滔。
-
log(self, message[, level, component])
使用 scrapy.log.msg() 方法記錄(log)message惠毁。 更多數(shù)據(jù)請參見 logging
案例:騰訊招聘網(wǎng)自動翻頁采集
-
創(chuàng)建一個新的爬蟲:
scrapy genspider tencent "tencent.com"
-
編寫items.py
獲取職位名稱、詳細信息崎页、 class TencentItem(scrapy.Item): name = scrapy.Field() detailLink = scrapy.Field() positionInfo = scrapy.Field() peopleNumber = scrapy.Field() workLocation = scrapy.Field() publishTime = scrapy.Field()
-
編寫tencent.py
# tencent.py from mySpider.items import TencentItem import scrapy import re class TencentSpider(scrapy.Spider): name = "tencent" allowed_domains = ["hr.tencent.com"] start_urls = [ "http://hr.tencent.com/position.php?&start=0#a" ] def parse(self, response): for each in response.xpath('//*[@class="even"]'): item = TencentItem() name = each.xpath('./td[1]/a/text()').extract()[0] detailLink = each.xpath('./td[1]/a/@href').extract()[0] positionInfo = each.xpath('./td[2]/text()').extract()[0] peopleNumber = each.xpath('./td[3]/text()').extract()[0] workLocation = each.xpath('./td[4]/text()').extract()[0] publishTime = each.xpath('./td[5]/text()').extract()[0] #print name, detailLink, catalog, peopleNumber, workLocation,publishTime item['name'] = name.encode('utf-8') item['detailLink'] = detailLink.encode('utf-8') item['positionInfo'] = positionInfo.encode('utf-8') item['peopleNumber'] = peopleNumber.encode('utf-8') item['workLocation'] = workLocation.encode('utf-8') item['publishTime'] = publishTime.encode('utf-8') curpage = re.search('(\d+)',response.url).group(1) page = int(curpage) + 10 url = re.sub('\d+', str(page), response.url) # 發(fā)送新的url請求加入待爬隊列鞠绰,并調(diào)用回調(diào)函數(shù) self.parse yield scrapy.Request(url, callback = self.parse) # 將獲取的數(shù)據(jù)交給pipeline yield item
-
編寫pipeline.py文件
import json #class ItcastJsonPipeline(object): class TencentJsonPipeline(object): def __init__(self): #self.file = open('teacher.json', 'wb') self.file = open('tencent.json', 'wb') def process_item(self, item, spider): content = json.dumps(dict(item), ensure_ascii=False) + "\n" self.file.write(content) return item def close_spider(self, spider): self.file.close()
-
在 setting.py 里設(shè)置ITEM_PIPELINES
ITEM_PIPELINES = { #'mySpider.pipelines.SomePipeline': 300, #"mySpider.pipelines.ItcastJsonPipeline":300 "mySpider.pipelines.TencentJsonPipeline":300 }
執(zhí)行爬蟲:scrapy crawl tencent
思考
請思考 parse()方法的工作機制:
1. 因為使用的yield,而不是return飒焦。parse函數(shù)將會被當(dāng)做一個生成器使用蜈膨。scrapy會逐一獲取parse方法中生成的結(jié)果,并判斷該結(jié)果是一個什么樣的類型牺荠;
2. 如果是request則加入爬取隊列翁巍,如果是item類型則使用pipeline處理,其他類型則返回錯誤信息志电。
3. scrapy取到第一部分的request不會立馬就去發(fā)送這個request曙咽,只是把這個request放到隊列里,然后接著從生成器里獲忍袅尽;
4. 取盡第一部分的request孝情,然后再獲取第二部分的item鱼蝉,取到item了,就會放到對應(yīng)的pipeline里處理箫荡;
5. parse()方法作為回調(diào)函數(shù)(callback)賦值給了Request魁亦,指定parse()方法來處理這些請求 scrapy.Request(url, callback=self.parse)
6. Request對象經(jīng)過調(diào)度,執(zhí)行生成 scrapy.http.response()的響應(yīng)對象羔挡,并送回給parse()方法洁奈,直到調(diào)度器中沒有Request(遞歸的思路)
7. 取盡之后,parse()工作結(jié)束绞灼,引擎再根據(jù)隊列和pipelines中的內(nèi)容去執(zhí)行相應(yīng)的操作利术;
8. 程序在取得各個頁面的items前,會先處理完之前所有的request隊列里的請求低矮,然后再提取items印叁。
7. 這一切的一切,Scrapy引擎和調(diào)度器將負責(zé)到底军掂。