Scrapy架構CrawlSpiders的介紹以及使用詳解,scrapycrawlspiders

來源:互聯網
上載者:User

Scrapy架構CrawlSpiders的介紹以及使用詳解,scrapycrawlspiders

在Scrapy基礎——Spider中,我簡要地說了一下Spider類。Spider基本上能做很多事情了,但是如果你想爬取知乎或者是簡書全站的話,你可能需要一個更強大的武器。CrawlSpider基於Spider,但是可以說是為全站爬取而生。

CrawlSpiders是Spider的衍生類別,Spider類的設計原則是只爬取start_url列表中的網頁,而CrawlSpider類定義了一些規則(rule)來提供跟進link的方便的機制,從爬取的網頁中擷取link並繼續爬取的工作更適合。

一、我們先來分析一下CrawlSpiders源碼

源碼解析class CrawlSpider(Spider):  rules = ()  def __init__(self, *a, **kw):    super(CrawlSpider, self).__init__(*a, **kw)    self._compile_rules()  # 首先調用parse()來處理start_urls中返回的response對象  # parse()則將這些response對象傳遞給了_parse_response()函數處理,並設定回呼函數為parse_start_url()  # 設定了跟進標誌位True  # parse將返回item和跟進了的Request對象    def parse(self, response):    return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True)  # 處理start_url中返回的response,需要重寫  def parse_start_url(self, response):    return []  def process_results(self, response, results):    return results  # 從response中抽取符合任一使用者定義'規則'的連結,並構造成Resquest對象返回  def _requests_to_follow(self, response):    if not isinstance(response, HtmlResponse):      return    seen = set()    # 抽取之內的所有連結,只要通過任意一個'規則',即表示合法    for n, rule in enumerate(self._rules):      links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]      # 使用使用者指定的process_links處理每個串連      if links and rule.process_links:        links = rule.process_links(links)      # 將連結加入seen集合,為每個連結產生Request對象,並設定回呼函數為_repsonse_downloaded()      for link in links:        seen.add(link)        # 構造Request對象,並將Rule規則中定義的回呼函數作為這個Request對象的回呼函數        r = Request(url=link.url, callback=self._response_downloaded)        r.meta.update(rule=n, link_text=link.text)        # 對每個Request調用process_request()函數。該函數預設為indentify,即不做任何處理,直接返回該Request.        yield rule.process_request(r)  # 處理通過rule提取出的串連,並返回item以及request  def _response_downloaded(self, response):    rule = self._rules[response.meta['rule']]    return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow)  # 解析response對象,會用callback解析處理他,並返回request或Item對象  def _parse_response(self, response, callback, cb_kwargs, follow=True):    # 首先判斷是否設定了回呼函數。(該回呼函數可能是rule中的解析函數,也可能是 parse_start_url函數)    # 如果設定了回呼函數(parse_start_url()),那麼首先用parse_start_url()處理response對象,    # 然後再交給process_results處理。返回cb_res的一個列表    if callback:      #如果是parse調用的,則會解析成Request對象      #如果是rule callback,則會解析成Item      cb_res = callback(response, **cb_kwargs) or ()      cb_res = self.process_results(response, cb_res)      for requests_or_item in iterate_spider_output(cb_res):        yield requests_or_item    # 如果需要跟進,那麼使用定義的Rule規則提取並返回這些Request對象    if follow and self._follow_links:      #返回每個Request對象      for request_or_item in self._requests_to_follow(response):        yield request_or_item  def _compile_rules(self):    def get_method(method):      if callable(method):        return method      elif isinstance(method, basestring):        return getattr(self, method, None)    self._rules = [copy.copy(r) for r in self.rules]    for rule in self._rules:      rule.callback = get_method(rule.callback)      rule.process_links = get_method(rule.process_links)      rule.process_request = get_method(rule.process_request)  def set_crawler(self, crawler):    super(CrawlSpider, self).set_crawler(crawler)    self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True)

二、 CrawlSpider爬蟲檔案欄位的介紹

1、 CrawlSpider繼承於Spider類,除了繼承過來的屬性外(name、allow_domains),還提供了新的屬性和方法:class scrapy.linkextractors.LinkExtractorLink Extractors 的目的很簡單: 提取連結。每個LinkExtractor有唯一的公用方法是 extract_links(),它接收一個 Response 對象,並返回一個 scrapy.link.Link 對象。

Link Extractors要執行個體化一次,並且 extract_links 方法會根據不同的 response 調用多次提取連結。

class scrapy.linkextractors.LinkExtractor(  allow = (),  deny = (),  allow_domains = (),  deny_domains = (),  deny_extensions = None,  restrict_xpaths = (),  tags = ('a','area'),  attrs = ('href'),  canonicalize = True,  unique = True,  process_value = None)

主要參數:

① allow:滿足括弧中“Regex”的值會被提取,如果為空白,則全部匹配。
② deny:與這個Regex(或Regex列表)不匹配的URL一定不提取。
③ allow_domains:會被提取的連結的domains。
④ deny_domains:一定不會被提取連結的domains。
⑤ restrict_xpaths:使用xpath運算式,和allow共同作用過濾連結。

2、 在rules中包含一個或多個Rule對象,每個Rule對爬取網站的動作定義了特定操作。如果多個rule匹配了相同的連結,則根據規則在本集合中被定義的順序,第一個會被使用。

class scrapy.spiders.Rule(    link_extractor,     callback = None,     cb_kwargs = None,     follow = None,     process_links = None,     process_request = None)

① link_extractor:是一個Link Extractor對象,用於定義需要提取的連結。

② callback: 從link_extractor中每擷取到連結時,參數所指定的值作為回呼函數,該回呼函數接受一個response作為其第一個參數。

注意:當編寫爬蟲規則時,避免使用parse作為回呼函數。由於CrawlSpider使用parse方法來實現其邏輯,如果覆蓋了 parse方法,crawl spider將會運行失敗。

③ follow:是一個布爾(boolean)值,指定了根據該規則從response提取的連結是否需要跟進。 如果callback為None,follow 預設設定為True ,否則預設為False。

④ process_links:指定該spider中哪個的函數將會被調用,從link_extractor中擷取到連結清單時將會調用該函數。該方法主要用來過濾。

⑤ process_request:指定該spider中哪個的函數將會被調用, 該規則提取到每個request時都會調用該函數。 (用來過濾request)

3、Scrapy提供了log功能,可以通過 logging 模組使用。可以修改設定檔settings.py,任意位置添加下面兩行,效果會清爽很多。

LOG_FILE = "TencentSpider.log"LOG_LEVEL = "INFO"

Scrapy提供5層logging層級:

① CRITICAL - 嚴重錯誤(critical)
② ERROR - 一般錯誤(regular errors)
③ WARNING - 警告資訊(warning messages)
④ INFO - 一般資訊(informational messages)
⑤ DEBUG - 調試資訊(debugging messages)

通過在setting.py中進行以下設定可以被用來配置logging:

① LOG_ENABLED 預設: True,啟用logging
② LOG_ENCODING 預設: 'utf-8',logging使用的編碼
③ LOG_FILE 預設: None,在目前的目錄裡建立logging輸出檔案的檔案名稱
④ LOG_LEVEL 預設: 'DEBUG',log的最低層級
⑤ LOG_STDOUT 預設: False 如果為 True,進程所有的標準輸出(及錯誤)將會被重新導向到log中。例如,執行 print "hello" ,其將會在Scrapy log中顯示。

三、 CrawlSpider爬蟲案例分析

1、建立項目:scrapy startproject CrawlYouYuan

2、建立爬蟲檔案:scrapy genspider -t crawl youyuan youyuan.com

3、專案檔分析

items.py

模型類import scrapyclass CrawlyouyuanItem(scrapy.Item):  # 使用者名稱  username = scrapy.Field()  # 年齡  age = scrapy.Field()  # 頭像圖片的連結  header_url = scrapy.Field()  # 相簿圖片的連結  images_url = scrapy.Field()  # 內心獨白  content = scrapy.Field()  # 籍貫  place_from = scrapy.Field()  # 學曆  education = scrapy.Field()  # 興趣愛好  hobby = scrapy.Field()  # 個人首頁  source_url = scrapy.Field()  # 資料來源網站  sourec = scrapy.Field()  # utc 時間  time = scrapy.Field()  # 爬蟲名  spidername = scrapy.Field()

youyuan.py

爬蟲檔案# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom CrawlYouYuan.items import CrawlyouyuanItemimport reclass YouyuanSpider(CrawlSpider):  name = 'youyuan'  allowed_domains = ['youyuan.com']  start_urls = ['http://www.youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p1/']  # 自動產生的檔案不需要改東西,只需要添加rules檔案裡面Rule角色就可以  # 每一頁匹配規則  page_links = LinkExtractor(allow=(r"youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p\d+/"))  # 每個人個人首頁匹配規則  profile_links = LinkExtractor(allow=(r"youyuan.com/\d+-profile/"))  rules = (    # 沒有回呼函數,說明follow是True    Rule(page_links),    # 有回呼函數,說明follow是False    Rule(profile_links, callback='parse_item', follow=True),  )  def parse_item(self, response):    item = CrawlyouyuanItem()    item['username'] = self.get_username(response)    # 年齡    item['age'] = self.get_age(response)    # 頭像圖片的連結    item['header_url'] = self.get_header_url(response)    # 相簿圖片的連結    item['images_url'] = self.get_images_url(response)    # 內心獨白    item['content'] = self.get_content(response)    # 籍貫    item['place_from'] = self.get_place_from(response)    # 學曆    item['education'] = self.get_education(response)    # 興趣愛好    item['hobby'] = self.get_hobby(response)    # 個人首頁    item['source_url'] = response.url    # 資料來源網站    item['sourec'] = "youyuan"    yield item  def get_username(self, response):    username = response.xpath("//dl[@class='personal_cen']//div[@class='main']/strong/text()").extract()    if len(username):      username = username[0]    else:      username = "NULL"    return username.strip()  def get_age(self, response):    age = response.xpath("//dl[@class='personal_cen']//dd/p/text()").extract()    if len(age):      age = re.findall(u"\d+歲", age[0])[0]    else:      age = "NULL"    return age.strip()  def get_header_url(self, response):    header_url = response.xpath("//dl[@class='personal_cen']/dt/img/@src").extract()    if len(header_url):      header_url = header_url[0]    else:      header_url = "NULL"    return header_url.strip()  def get_images_url(self, response):    images_url = response.xpath("//div[@class='ph_show']/ul/li/a/img/@src").extract()    if len(images_url):      images_url = ", ".join(images_url)    else:      images_url = "NULL"    return images_url  def get_content(self, response):    content = response.xpath("//div[@class='pre_data']/ul/li/p/text()").extract()    if len(content):      content = content[0]    else:      content = "NULL"    return content.strip()  def get_place_from(self, response):    place_from = response.xpath("//div[@class='pre_data']/ul/li[2]//ol[1]/li[1]/span/text()").extract()    if len(place_from):      place_from = place_from[0]    else:      place_from = "NULL"    return place_from.strip()  def get_education(self, response):    education = response.xpath("//div[@class='pre_data']/ul/li[3]//ol[2]/li[2]/span/text()").extract()    if len(education):      education = education[0]    else:      education = "NULL"    return education.strip()  def get_hobby(self, response):    hobby = response.xpath("//dl[@class='personal_cen']//ol/li/text()").extract()    if len(hobby):      hobby = ",".join(hobby).replace(" ", "")    else:      hobby = "NULL"    return hobby.strip()

pipelines.py

管道檔案import jsonimport codecsclass CrawlyouyuanPipeline(object):  def __init__(self):    self.filename = codecs.open('content.json', 'w', encoding='utf-8')  def process_item(self, item, spider):    html = json.dumps(dict(item), ensure_ascii=False)    self.filename.write(html + '\n')    return item  def spider_closed(self, spider):    self.filename.close()

settings.py

BOT_NAME = 'CrawlYouYuan'SPIDER_MODULES = ['CrawlYouYuan.spiders']NEWSPIDER_MODULE = 'CrawlYouYuan.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agentUSER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:56.0)'# Obey robots.txt rulesROBOTSTXT_OBEY = TrueITEM_PIPELINES = {  'CrawlYouYuan.pipelines.CrawlyouyuanPipeline': 300,}

begin.py

from scrapy import cmdlinecmdline.execute('scrapy crawl youyuan'.split())

在運行程式之前需要使Scrapy版本和Twisted版本相吻合,設定如下

這次分享詳細介紹了使用Scrapy架構爬蟲的具體步驟,並同時編寫爬蟲案例進行分析,很好的詮釋了Scrapy架構爬取資料的方便性和易懂性,下篇文章我會分享下Scrapy分布式爬取網站,讓我們一起學習,一起探討爬蟲技術。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.