創(chuàng)建爬蟲項(xiàng)目
首先確保在Python環(huán)境下安裝好Scrapy衔统。具體過程可以參考我之前的文章
Python環(huán)境下Scrapy爬蟲框架安裝
進(jìn)入windows的cmd或mac終端在某文件目錄(這里為craw文件夾)下創(chuàng)建爬蟲項(xiàng)目bookpjt,并進(jìn)入該項(xiàng)目文件夾
scrapy startproject bookpjt
cd bookpjt
項(xiàng)目修改
這里我們選擇爬取當(dāng)當(dāng)網(wǎng)python書籍商品的書名,價(jià)格橘蜜,鏈接锋叨,評論數(shù)等數(shù)據(jù)垄分。
進(jìn)入項(xiàng)目文件目錄下,找到并修改items.py文件悲柱,未修改前該文件如下:
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class BookpjtItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
修改類BookpjtItem如下:
class BookpjtItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
#定義好name用來存儲商品名
name=scrapy.Field()
#定義好price用來存儲商品價(jià)格
price=scrapy.Field()
#定義好link用來存儲商品鏈接
link=scrapy.Field()
#定義好comnum用來存儲商品評論數(shù)
comnum=scrapy.Field()
修改pipelines.py文件锋喜,我們要將爬取到的數(shù)據(jù)存儲在.json文件中,注意修改輸出的.json文件路徑為你自己電腦的路徑豌鸡。
# -*- coding: utf-8 -*-
import codecs
import json
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class AutopjtPipeline(object):
def __init__(self):
#此時(shí)存儲到的文件是getdata.json,注意這里將路徑修改為你自己要保存文件的路徑嘿般!
self.file = codecs.open("D:/python/.../getdata.json", "wb", encoding="utf-8")
def process_item(self, item, spider):
#每一頁中包含多個商品信息,所以可以通過循環(huán)涯冠,每一次處理一個商品
#其中l(wèi)en(item["name"])為當(dāng)前頁中商品的總數(shù)炉奴,依次遍歷
for j in range(0,len(item["name"])):
#將當(dāng)前頁的第j個商品的名稱賦值給變量name
name=item["name"][j]
price=item["price"][j]
comnum=item["comnum"][j]
link=item["link"][j]
#將當(dāng)前頁下第j個商品的name、price蛇更、comnum瞻赶、link等信息處理一下
#重新組合成一個字典
books={"name":name,"price":price,"comnum":comnum,"link":link}
#將組合后的當(dāng)前頁中第j個商品的數(shù)據(jù)寫入json文件
i=json.dumps(dict(books), ensure_ascii=False)
line = i + '\n'
self.file.write(line)
#返回item
return item
def close_spider(self,spider):
self.file.close()
接下來修改setting.py文件赛糟,首先開啟pipelines,取消這三行的注釋即可。
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'bookpjt.pipelines.BookpjtPipeline': 300,
}
因?yàn)橐恍┚W(wǎng)站可能會有反爬蟲機(jī)制砸逊,會屏蔽你的Cookie璧南,這里作Cookie反屏蔽處理
# Disable cookies (enabled by default)
COOKIES_ENABLED = False
有時(shí)爬蟲會因?yàn)槲醋袷豶obots.txt規(guī)則而不能運(yùn)行,這里將robots.txt規(guī)則設(shè)為False师逸,當(dāng)然保證你的爬取行為合理合法司倚。
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
以上修改均可以在setting.py文件中。
創(chuàng)建爬蟲文件
回到cmd或者終端篓像,在該項(xiàng)目目錄下以basic爬蟲模板創(chuàng)建爬蟲文件
scrapy genspider -t basic myspd dangdang.com
在當(dāng)當(dāng)網(wǎng)中搜索python动知,分析當(dāng)當(dāng)網(wǎng)python書籍商品網(wǎng)址,可發(fā)現(xiàn)index后即為商品頁數(shù)员辩,可以多翻幾頁試試盒粮,第一頁也許會和后面的頁網(wǎng)址不一樣,但是后面頁網(wǎng)址的結(jié)構(gòu)也可以打開第一頁奠滑。
http://search.dangdang.com/?key=python&act=input&show=big&page_index=1#J_tab
http://search.dangdang.com/?key=python&act=input&show=big&page_index=2#J_tab
······
分析網(wǎng)頁源代碼丹皱,提取書名,價(jià)格宋税,鏈接种呐,評論數(shù)的XPath表達(dá)式,如"http://a[@class='pic']/@title"為class屬性為pic的a標(biāo)簽中的title屬性對應(yīng)的值弃甥。
編寫myspd.py文件
# -*- coding: utf-8 -*-
import scrapy
from bookpjt.items import BookpjtItem
from scrapy.http import Request
class MyspdSpider(scrapy.Spider):
name = "myspd"
allowed_domains = ["dangdang.com"]
start_urls = ['http://search.dangdang.com/?key=python&act=input&show=big&page_index=1#J_tab']
def parse(self, response):
item=BookpjtItem()
#通過各Xpath表達(dá)式分別提取商品的名稱、價(jià)格汁讼、鏈接淆攻、評論數(shù)等信息
item["name"]=response.xpath("http://a[@class='pic']/@title").extract()
item["price"]=response.xpath("http://span[@class='price_n']/text()").extract()
item["link"]=response.xpath("http://a[@class='pic']/@href").extract()
item["comnum"]=response.xpath("http://a[@name='itemlist-review']/text()").extract()
#提取完后返回item
yield item
#接下來很關(guān)鍵,通過循環(huán)自動爬取20頁的數(shù)據(jù)
for i in range(1,21):
#通過上面總結(jié)的網(wǎng)址格式構(gòu)造要爬取的網(wǎng)址
url="http://search.dangdang.com/?key=python&act=input&show=big&page_index="+str(i)+"#J_tab"
#通過yield返回Request嘿架,并指定要爬取的網(wǎng)址和回調(diào)函數(shù)
#實(shí)現(xiàn)自動爬取
yield Request(url, callback=self.parse)
調(diào)試運(yùn)行爬蟲
返回項(xiàng)目目錄下瓶珊,在cmd或終端調(diào)試運(yùn)行爬蟲
scrapy crawl myspd --nolog
在你之前保存的目錄下查看getdata.json文件,可以看到很快爬蟲便爬取了近1000多本書的數(shù)據(jù)信息。若沒有文件或者文件內(nèi)容為空耸彪,校對以上步驟看看哪里出錯了伞芹。
本文是快速成功實(shí)現(xiàn)了一個爬蟲,同理蝉娜,可以對其他網(wǎng)站或者其他商品通過Scrapy爬蟲爬取你所需的數(shù)據(jù)信息唱较。做法是分析網(wǎng)址源碼,改動一下數(shù)據(jù)結(jié)構(gòu)和正則表達(dá)式召川,具體內(nèi)容可以百度搜索研究學(xué)習(xí)XPath表達(dá)式部分南缓。
獲取到數(shù)據(jù)后就可以進(jìn)一步的進(jìn)行數(shù)據(jù)分析或可視化,玩起這份自己獲取到的數(shù)據(jù)啦_荧呐。具體內(nèi)容以后玩到也會分享展示出來的汉形。
項(xiàng)目代碼已上傳至我的github|ChocoYvan纸镊,可以fork下來參考。
歡迎參觀我的博客|巧不巧克力,一起交流學(xué)習(xí)哈O(∩_∩)O