pip是作為python包索引器easy_install的替代品,用于安裝和管理Python包。pip包的安裝可見圖 1。
sudo apt-get install python-pip
圖:1 pip安裝
我們必須要用下面的命令安裝python開發(fā)庫。如果包沒有安裝那么就會在安裝scrapy框架的時候報關(guān)于python.h頭文件的錯誤。
sudo apt-get install python-dev
圖:2 Python 開發(fā)庫
scrapy框架既可從deb包安裝也可以從源碼安裝。在圖3中我們用pip(Python 包管理器)安裝了deb包了。
sudo pip install scrapy
圖:3 Scrapy 安裝
圖4中scrapy的成功安裝需要一些時間。
圖:4 成功安裝Scrapy框架
使用scrapy框架提取數(shù)據(jù)
基礎(chǔ)教程
我們將用scrapy從fatwallet.com上提取商店名稱(賣卡的店)。首先,我們使用下面的命令新建一個scrapy項目“store name”, 見圖5。
$sudo scrapy startproject store_name
圖:5 Scrapy框架新建項目
上面的命令在當(dāng)前路徑創(chuàng)建了一個“store_name”的目錄。項目主目錄下包含的文件/文件夾見圖6。
$sudo ls –lR store_name
圖:6 store_name項目的內(nèi)容
每個文件/文件夾的概要如下:
由于我們要從fatwallet.com上如提取店名,因此我們?nèi)缦滦薷奈募↙CTT 譯注:這里沒說明是哪個文件,譯者認為應(yīng)該是 items.py)。
import scrapy class StoreNameItem(scrapy.Item): name = scrapy.Field() # 取出卡片商店的名稱
之后我們要在項目的store_name/spiders/文件夾下寫一個新的蜘蛛。蜘蛛是一個python類,它包含了下面幾個必須的屬性:
我們在storename/spiders/目錄下創(chuàng)建了“storename.py”爬蟲,并添加如下的代碼來從fatwallet.com上提取店名。爬蟲的輸出寫到文件(StoreName.txt)中,見圖7。
from scrapy.selector import Selector from scrapy.spider import BaseSpider from scrapy.http import Request from scrapy.http import FormRequest import re class StoreNameItem(BaseSpider): name = "storename" allowed_domains = ["fatwallet.com"] start_urls = ["http://fatwallet.com/cash-back-shopping/"] def parse(self,response): output = open('StoreName.txt','w') resp = Selector(response) tags = resp.xpath('//tr[@class="storeListRow"]| //tr[@class="storeListRow even"]| //tr[@class="storeListRow even last"]| //tr[@class="storeListRow last"]').extract() for i in tags: i = i.encode('utf-8', 'ignore').strip() store_name = '' if re.search(r"class="storeListStoreName">.*?<",i,re.I|re.S): store_name = re.search(r"class="storeListStoreName">.*?<",i,re.I|re.S).group() store_name = re.search(r">.*?<",store_name,re.I|re.S).group() store_name = re.sub(r'>',"",re.sub(r'<',"",store_name,re.I)) store_name = re.sub(r'&',"&",re.sub(r'&',"&",store_name,re.I)) #print store_name output.write(store_name+""+" ")
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com