1. 程式人生 > >爬蟲實踐之爬蟲框架Scrapy安裝

爬蟲實踐之爬蟲框架Scrapy安裝

1.爬蟲框架Scarpy

Scrapy 是一個快速的高層次的螢幕抓取和網頁爬蟲框架,爬取網站,從網站頁面得到結構化的資料,它有著廣泛的用途,從資料探勘到監測和自動測試,Scrapy完全用Python實現,完全開源,程式碼託管在Github上,可執行在Linux,Windows,Mac和BSD平臺上,基於Twisted的非同步網路庫來處理網路通訊,使用者只需要定製開發幾個模組就可以輕鬆的實現一個爬蟲,用來抓取網頁內容以及各種圖片。

2.Scrapy安裝指南

我們的安裝步驟假設你已經安裝一下內容:<1>Python2.7<2>lxml<3>OpenSSL,我們使用Python的包管理工具pip或者easy_install來安裝Scrapy。
pip的安裝方式:
pip install Scrapy
easy_install的安裝方式:
easy_install Scrapy

3.Ubuntu平臺上環境配置


3.1python的包管理工具

當前的包管理工具鏈是 easy_install/pip + distribute/setuptools
distutils : Python 自帶的基本安裝工具, 適用於非常簡單的應用場景;  setuptools : 針對 distutils 做了大量擴充套件, 尤其是加入了包依賴機制. 在部分 Python 子社群已然是事實上的標準;
distribute : 由於 setuptools 開發進度緩慢, 不支援 Python 3, 程式碼混亂, 一幫程式設計師另起爐灶, 重構程式碼, 增加功能, 希望能夠取代 setuptools 並被接納為官方標準庫, 他們非常努力, 在很短的時間便讓社群接受了 distribute;, setuptools / distribute 都只是擴充套件了 distutils; easy_install : setuptools 和 distribute 自帶的安裝指令碼, 也就是一旦 setuptools 或 distribute 安裝完畢, easy_install 也便可用. 最大的特點是自動查詢 Python 官方維護的包源 PyPI , 安裝第三方 Python 包非常方便; 使用:
pip : pip 的目標非常明確 – 取代 easy_install. easy_install 有很多不足: 安裝事務是非原子操作, 只支援 svn, 沒有提供解除安裝命令, 安裝一系列包時需要寫指令碼; pip 解決了以上問題, 已儼然成為新的事實標準, virtualenv 與它已經成為一對好搭檔;

安裝過程:

安裝distribute   

$ curl -O http://python-distribute.org/distribute_setup.py
$ python distribute_setup.py

安裝pip

$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ [sudo] python get-pip.py


3.2 Scrapy的安裝

在Windows平臺上,可以通過包管理工具或者手動下載各種依賴的二進位制包:pywin32,Twisted,zope.interface,lxml,pyOpenSSL,在Ubuntu9.10以後的版本上,官方推薦不用使用Ubuntu提供的python-scrapy包,它們要麼太老要麼太慢,無法匹配最新的Scrapy,解決方案是,使用官方的Ubuntu Packages,它提供了所有的依賴庫,並且對於最新的bug提供持續的更新,穩定性更高,它們持續的從Github倉庫(master和stable branches)構建,Scrapy在Ubuntu9.10之後的版本上的安裝方法如下: <1>輸入GPG金鑰

  
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 627220E7
<2>建立/etc/apt/sources.list.d/scrapy.list 檔案

  
echo 'deb http://archive.scrapy.org/ubuntu scrapy main' | sudo tee /etc/apt/sources.list.d/scrapy.list
<3>更新包列表,安裝scrapy版本,其中VERSION用實際的版本代替,如scrapy-0.22

  

  
sudo apt-get update && sudo apt-get install scrapy-VERSION

3.3Scrapy依賴庫的安裝


  
   ubuntu12.04下scrapy依賴庫的安裝
  
  
    
  
  
   ImportError: No module named w3lib.http
  
  
   
pip install w3lib
ImportError: No module named twisted
pip install twisted
ImportError: No module named lxml.html
pip install lxml
error: libxml/xmlversion.h: No such file or directory 解決:
apt-get install libxml2-dev libxslt-dev
apt-get install python-lxml
ImportError: No module named cssselect 解決:
pip install cssselect
ImportError: No module named OpenSSL
pip install pyOpenSSL

4.定製自己的爬蟲開發

切換到檔案目錄,開啟新的工程

  
scrapy startproject test