Crawlspider
一:Crawlspider簡介
CrawlSpider其實是Spider的一個子類,除了繼承到Spider的特性和功能外,還派生除了其自己獨有的更加強大的特性和功能。其中最顯著的功能就是”LinkExtractors鏈接提取器“。Spider是所有爬蟲的基類,其設計原則只是為了爬取start_url列表中網頁,而從爬取到的網頁中提取出的url進行繼續的爬取工作使用CrawlSpider更合適。
二:CrawlSpider整體的爬取流程:
a)爬蟲文件首先根據其實url,獲取該url的網頁內容
b)鏈接提取器會根據提取規則將步驟a中網頁內容中的鏈接進行提取
c)規則解析器會根據指定解析規則將鏈接提取器中提取到的鏈接中的網頁內容根據指定的規則進行解析
d)將解析數據封裝到item中,然后提交給管道進行持久化存儲
三:Crawlspider使用
實例:爬取https://www.qiushibaike.com/主頁帖子作者以及內容
1.創建scrapy工程
2.創建爬蟲文件
注意:對比以前的指令多了 "-t crawl",表示創建的爬蟲文件是基於CrawlSpider這個類的,而不再是Spider這個基類。
3.生成的目錄結構如下:
CrawlDemo.py爬蟲文件設置:
LinkExtractor:顧名思義,鏈接提取器。
Rule : 規則解析器。根據鏈接提取器中提取到的鏈接,根據指定規則提取解析器鏈接網頁中的內容。
Rule參數介紹:
參數1:指定鏈接提取器
參數2:指定規則解析器解析數據的規則(回調函數)
參數3:是否將鏈接提取器繼續作用到鏈接提取器提取出的鏈接網頁中,當callback為None,參數3的默認值為true。
rules=( ):指定不同規則解析器。一個Rule對象表示一種提取規則。
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from crawlPro.items import CrawlproItem class CrawldemoSpider(CrawlSpider): name = 'crawlDemo' # allowed_domains = ['www.qiushibaike.com'] start_urls = ['http://www.qiushibaike.com/'] #rules元祖中存放的是不同規則解析器(封裝好了某種解析規則) rules = ( # Rule: 規則解析器,可以將連接提取器提取到的所有連接表示的頁面進行指定規則(有中間的回調函數決定)的解析 #LinkBxtractor:連接提取器,會去上面起始url響應回來的頁面中,提取指定的url Rule(LinkExtractor(allow=r'/8hr/page/\d+'), callback='parse_item', follow=True), #follow=True可以跟進保證將所有頁面都提取出來(實際就是去重功能) ) def parse_item(self, response): # i = {} # #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract() # #i['name'] = response.xpath('//div[@id="name"]').extract() # #i['description'] = response.xpath('//div[@id="description"]').extract() # return i divs=response.xpath('//div[@id="content-left"]/div') for div in divs: item=CrawlproItem() #提取糗百中段子的作者 item['author'] = div.xpath('./div[@class="author clearfix"]/a[2]/h2/text()').extract_first().strip('\n') # 提取糗百中段子的內容 item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first().strip('\n') yield item #將item提交到管道
item.py文件設置:
# -*- 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 CrawlproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author=scrapy.Field() content=scrapy.Field()
pipelines.py管道文件設置:
# -*- 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 class CrawlproPipeline(object): def __init__(self): self.fp = None def open_spider(self,spider): print('開始爬蟲') self.fp = open('./data.txt','w',encoding='utf-8') def process_item(self, item, spider): # 將爬蟲文件提交的item寫入文件進行持久化存儲 self.fp.write(item['author']+':'+item['content']+'\n') return item def close_spider(self,spider): print('結束爬蟲') self.fp.close()
設置代理:
middlewares.py中間件:
設置代理:ip地址可以通過以下幾個鏈接查找
http://ip.seofangfa.com/
settings.py里面設置:
DOWNLOADER_MIDDLEWARES = {
'crawlPro.middlewares.Mydaili': 543, #Mydaili名字就是中間件里面的類名
}
middlewares.py中間件設置:
class Mydaili(object):
def process_request(self,request,spider):
request.meta['proxy'] = "http://119.28.195.93:8888"