剛"會(huì)爬"就想"飛"的蟲子(基于 Scrapy)

大家好,我是一個(gè)"沾沾自喜"的蟲子,剛剛學(xué)會(huì)寫一點(diǎn)點(diǎn)代碼,明白了"爬"的原理,就想要"飛"了,于是"摔"的很慘.不過,這也是成長(zhǎng)的過程.也許當(dāng)我回頭看的時(shí)候,自己會(huì)笑噴.還是比較享受這個(gè)過程的.


Scrapy

Scrapy是一個(gè)為了爬取網(wǎng)站數(shù)據(jù),提取結(jié)構(gòu)性數(shù)據(jù)而編寫的應(yīng)用框架。 可以應(yīng)用在包括數(shù)據(jù)挖掘,信息處理或存儲(chǔ)歷史數(shù)據(jù)等一系列的程序中。

爬取數(shù)據(jù)

首先我們來一起爬取一下豆瓣電影上的數(shù)據(jù)吧..come on,

這個(gè)是要爬取數(shù)據(jù)的地址

https://movie.douban.com/top250

新建一個(gè)工程

scrapy startproject? doubandianying

Item

item 模塊個(gè)人理解為一種 model,說白了,就是把數(shù)據(jù)爬取下來之后放到這個(gè)容器中,之后可以用 pipelines 文存取到數(shù)據(jù)庫(kù)中. (本文不涉及到) .

修改 items.py 文件

打開文件可以看到結(jié)構(gòu),而且有例子,很簡(jiǎn)單.把想要的數(shù)據(jù)在這里寫好.寫spider文件的時(shí)候會(huì)需要.

import scrapy

class DoubandianyingItem(scrapy.Item):

? ? ?# define the fields for your item here like:

? ? ?# name = scrapy.Field()

? ? ? title = scrapy.Field()

? ? ? link = scrapy.Field()

? ? ? star = scrapy.Field()

? ? ? quote = scrapy.Field()

? ? ? pass

這里是想取的數(shù)據(jù):


Spider 文件

接下來就是寫爬蟲嘍,話不多說直接上代碼.

import scrapy

import sys

from doubandianying.items import DoubandianyingItem

reload(sys)

sys.setdefaultencoding('utf-8')

class doubandianying(scrapy.Spider):

? ? ? ? name ='doubandianying'

? ? ? ? allowed_domains = ["douban.com"]

? ? ? ?start_urls = ["http://movie.douban.com/top250/"]

? ? ?def ?parse(self,response):

? ? ? ? ?item = DoubandianyingItem()

? ? ? ? ?infos = response.xpath('//div[@class="item"]')

? ? ? ? ?for info in ? infos:

? ? ? ? ? ? ? ? title = info.xpath('div[@class="pic"]/a/img/@alt').extract()

? ? ? ? ? ? ? ?link= info.xpath('div[@class="pic"]/a/@href').extract()

? ? ? ? ? ? ? star = ? ? ? ? ? ? ?info.xpath('div[@class="info"]/div[@class="bd"]/div[@class="star"]/span[@class="rating_num"]/text()').extract()

? ? ? ? ? ? quote = info.xpath('div[@class="info"]/div[@class="bd"]/p[@class="quote"]/span/text()').extract()

? ? ? ? ? ?item['title']= title

? ? ? ? ? item['link']=link

? ? ? ? ? item['star']=star

? ? ? ? ? item['quote']=quote

? ? ? ? ?yield ?item

? ? ? ? next_page = response.xpath('//span[@class="next"]/a/@href')

? ? ? ? ?if next_page:

? ? ? ? ? ? ? ? ? ?url = response.urljoin(next_page[0].extract())

? ? ? ? ? ? ? ? ? ?yield scrapy.Request(url,self.parse)


一切都 OK 了,剩下的就是去爬蟲文件所在的目錄去執(zhí)行

scrapy crawl doubandianying

之后如果想看的方便點(diǎn),可以導(dǎo)出成.csv 格式或者 json 的形式.

scrapy crawl doubandianying -o items.json

如果還有什么地方有問題大家可以在評(píng)論里面說說....歡迎.

最后

想說一句其實(shí)有了框架,進(jìn)行爬蟲很簡(jiǎn)單,主要還是對(duì)于網(wǎng)頁(yè)的分析,XPath 語(yǔ)法要看看.傳送門,

如果看會(huì)了,不如試試抓一下豆瓣圖書去.加油

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容