日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

32-CrawlSpider类爬虫与Spider类爬虫比较-【都是基于Scrapy框架】

發布時間:2024/3/7 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 32-CrawlSpider类爬虫与Spider类爬虫比较-【都是基于Scrapy框架】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

任務:爬取“陽光熱線問政平臺的每個投訴信息(標題、編號、內容、鏈接)”? ?

要點:涉及翻頁

比較:這兩種方法都可以完成任務

  • 方法一使用CrawlSpider類,其中涉及Rule來解析網頁中的鏈接,比較簡單,但是可能會出現“假鏈接”
  • 方法二使用Spider類,需要自己手動拼接url,比較麻煩,但是不會出錯

一、采用CrawlSpider類完成該任務

分析:

(1)解析每個投訴信息

scrapy shell http://wz.sun0769.com/html/question/201905/412275.shtml #首先運行 response.url #返回當前網址 'http://wz.sun0769.com/html/question/201905/412275.shtml' response.xpath('//div[@class="wzy1"]//td[@valign="middle"]/span[1]/text()').extract()[0] #標題 response.xpath('//div[@class="wzy1"]//td[@valign="middle"]/span[2]/text()').extract()[0] #編號 response.xpath('//div[@class="wzy1"]//td[@class="txt16_3"]/text()').extract() #文本內容

(2)解析鏈接的爬取(每一頁的鏈接+每頁投訴信息的鏈接)

http://wz.sun0769.com/index.php/question/questionType?type=4&page=0 start_urls=[http://wz.sun0769.com/index.php/question/questionType?type=4&page=0]匹配下一頁的鏈接 Rule(LinkExtractor(allow=(r'type=4&page=\d+')),follow=True)#需要跟進,所以設置follow=True,但是不需要callback回調函數,因為該頁面不需要處理匹配每頁投訴信息的鏈接 Rule(LinkExtractor(allow=(r'/html/question/\d+/\d+.shtml')),callbakc=******)#不需要跟進,但是需要callback回調函數(處理投訴信息的內容)

注:一般情況下,沒有callback,follow默認為True;有callback,follow默認為False

總結:該例子需要兩個Rule來匹配鏈接

  • 第一個規則匹配下一頁的鏈接
  • 第二個規則匹配每頁有多少條鏈接,然后再進入該鏈接匹配每個投訴信息

1、在cmd中的基礎操作

C:\Users\Administrator\Desktop>scrapy startproject newsun C:\Users\Administrator\Desktop>cd newsun C:\Users\Administrator\Desktop\newsun>scrapy genspider -t crawl demo wz.sun0769.com

scrapy genspider -t crawl? 創建的是基于CrawlSpider類的爬蟲

2、編輯items.py,定義需要保存的字段

from scrapy import Field,Itemclass NewsunItem(Item):title=Field() #標題content=Field() #內容url=Field() #鏈接number=Field() #編號

3、在demo.py中編寫爬蟲文件

import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from newsun.items import NewsunItem import reclass DemoSpider(CrawlSpider): #基于CrawlSpider類的爬蟲name = 'demo'allowed_domains = ['wz.sun0769.com']start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=0']rules = (# 規則1:獲取下一頁鏈接,需要跟進follow=TrueRule(LinkExtractor(allow=r'type=4&page=\d+'),follow=True),#規則2:獲取每頁的投訴鏈接,不需要要跟進,使用callback='parse_item'處理Rule(LinkExtractor(allow=r'question/\d+/\d+.shtml'),callback='parse_item',follow=False),)"""在爬取每頁連接時,可能會給出:“假的鏈接”比如,真的下一頁為:http://wz.sun0679.com/index.php/question/questionType?page=3&type=4假的下一頁為:http://wz.sun0679.com/index.php/question/questionType&type=4?page=3即為:Type?和&的問題==>需要對爬取的下一頁鏈接進行處理"""def deal_links(self,links): #links是response里提取的鏈接列表(包括下一頁鏈接和每頁的投訴鏈接)for each in links:each.url=each.url.replace('?','&').replace('Type&','Type?')return linksdef parse_item(self, response):item=NewsunItem()item['url']=response.urlitem['title']=response.xpath('//div[@class="wzy1"]//td[@valign="middle"]/span[1]/text()').extract()[0].split(':')[-1]number=response.xpath('//div[@class="wzy1"]//td[@valign="middle"]/span[2]/text()').extract()[0]item['number']=re.findall('(\d+)',number)[0]content=response.xpath('//div[@class="wzy1"]//td[@class="txt16_3"]/text()').extract()content_str=''.join(content)item['content']=content_str.replace('\xa0','').replace(' ','')yield item

4、編輯pipelines.py,對爬取的item數據進行處理【此處僅僅保存】

import json class NewsunPipeline(object):def __init__(self):self.filename=open('newsun.json','w',encoding='utf-8')def process_item(self, item, spider):text=json.dumps(dict(item),ensure_ascii=False)self.filename.write(text+'\n')return itemdef close_spider(self):self.filename.close()

5、打開相應的settings.py中的pipeline配置

ITEM_PIPELINES = {'newsun.pipelines.NewsunPipeline': 300, }

6、運行

C:\Users\Administrator\Desktop\newsun>scrapy crawl demo

爬蟲完成,并且生成newsun.json文件

二、采用Spider類完成該任務

1、在cmd中的基礎操作

C:\Users\Administrator\Desktop>scrapy startproject oldsun C:\Users\Administrator\Desktop>cd oldsun C:\Users\Administrator\Desktop\oldsun>scrapy genspider demo wz.sun0769.com

scrapy genspider -t crawl? 創建的是基于CrawlSpider類的爬蟲

2、編輯items.py,定義需要保存的字段

from scrapy import Field,Itemclass NewsunItem(Item):title=Field() #標題content=Field() #內容url=Field() #鏈接number=Field() #編號

3、在demo.py中編寫爬蟲文件

import scrapy from oldsun.items import OldsunItem import reclass DemoSpider(scrapy.Spider): #基于Spider類的Scrapy框架name = 'demo'allowed_domains = ['wz.sun0769.com']url='http://wz.sun0769.com/index.php/question/questionType?type=4&page={}'page=0start_urls = [url.format(page)] #需要自己手動拼接urldef parse(self, response):links=response.xpath('//div[@class="greyframe"]//td/a[@class="news14"]/@href').extract()for link in links:yield scrapy.Request(link,callback=self.parse_item)if self.page<=71160:self.page+=30yield scrapy.Request(url=self.url.format(self.page),callback=self.parse)def parse_item(self,response):item=OldsunItem()item['url'] = response.urlitem['title'] = \response.xpath('//div[@class="wzy1"]//td[@valign="middle"]/span[1]/text()').extract()[0].split(':')[-1]number = response.xpath('//div[@class="wzy1"]//td[@valign="middle"]/span[2]/text()').extract()[0]item['number'] = re.findall('(\d+)', number)[0]content = response.xpath('//div[@class="wzy1"]//td[@class="txt16_3"]/text()').extract()content_str = ''.join(content)item['content'] = content_str.replace('\xa0', '').replace(' ', '')yield item

4、編輯pipelines.py,對爬取的item數據進行處理【此處僅僅保存】

import json class NewsunPipeline(object):def __init__(self):self.filename=open('newsun.json','w',encoding='utf-8')def process_item(self, item, spider):text=json.dumps(dict(item),ensure_ascii=False)self.filename.write(text+'\n')return itemdef close_spider(self):self.filename.close()

5、打開相應的settings.py中的pipeline配置

ITEM_PIPELINES = {'oldsun.pipelines.OldsunPipeline': 300, }

6、運行

C:\Users\Administrator\Desktop\oldsun>scrapy crawl demo

爬蟲完成,并且生成oldsun.json文件

轉載于:https://my.oschina.net/pansy0425/blog/3090154

總結

以上是生活随笔為你收集整理的32-CrawlSpider类爬虫与Spider类爬虫比较-【都是基于Scrapy框架】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。