Pyspider
Pyspider是國人開發的開源且強大的網絡爬蟲系統
python 腳本控制,可以用任何你喜歡的html解析包(內置 pyquery),WEB 界面編寫調試腳本,起停腳本,監控執行狀態,查看活動歷史,獲取結果產出,數據存儲支持MySQL, MongoDB, Redis, SQLite, Elasticsearch; PostgreSQL 及 SQLAlchemy,隊列服務支持RabbitMQ, Beanstalk, Redis 和 Kombu,支持抓取 JavaScript 的頁面。組件可替換,支持單機/分佈式部署,支持 Docker 部署。強大的調度控制,支持超時重爬及優先級設置。支持python2&3
在CentOS7 上安裝pyspider。
因爲Pyspider所依賴一個pycurl。而這個包比較特殊。需要使用源碼安裝。相關的鏈接http://www.linuxidc.com/Linux/2015-09/122805.htm
(鏈接時Ubuntu的,centos把 apt-get換成yum就好)
然後直接
pip install pyspider
另外需要再安裝 phantomjs。http://phantomjs.org/
phantomjs是一個無界面的瀏覽器。
在centos7 上啓動pyspider
[root@lol ~]# pyspider all
phantomjs fetcher running on port 25555
[I 171102 16:14:51 result_worker:49] result_worker starting...
[I 171102 16:14:51 processor:211] processor starting...
[I 171102 16:14:51 scheduler:647] scheduler starting...
[I 171102 16:14:52 scheduler:782] scheduler.xmlrpc listening on 127.0.0.1:23333
[I 171102 16:14:52 scheduler:586] in 5m: new:0,success:0,retry:0,failed:0
[I 171102 16:14:52 tornado_fetcher:638] fetcher starting...
[I 171102 16:14:52 app:76] webui running on 0.0.0.0:5000
在瀏覽器上訪問5000端口
接下來創建一個項目
下來進入到 調試運行代碼的界面。
接着演示一下 抓取貓途鷹旅遊網站的內容https://www.tripadvisor.cn/
假設我們要抓取這個網站的旅遊景點信息。那麼首先將被抓取網頁的url填入。
修改Handler類裏面的on_start方法:
@every(minutes=24 * 60)
def on_start(self):
self.crawl('__START_URL__', callback=self.index_page)
將裏面的 __START_URL__換成 要抓取的頁面。 點擊右上角的 Save 。再點 左邊的 run
運行結束會得到 一個url。點web有該頁面的 瀏覽。
再點擊url後的箭頭,會把該頁面全部的a標籤的 href 取出來。
沒錯。只要稍作修改就可以把該頁面的景區詳情的頁面抓出來。
還是修改 Hangler類。修改 index_page方法。
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
for each in response.doc('.attraction_element .listing_title > a').items():
self.crawl(each.attr.href, callback=self.detail_page)
根據 詳情頁面的一些特點就可以抓出來 想要的頁面。
接下來是如何處理抓到頁面的那些內容了。
@config(priority=2)
def detail_page(self, response):
name = response.doc(".heading_title").text()
rating = response.doc(".reviews_header_count").text()
address = response.doc(".location > .address").text()
phone = response.doc(".phone > div").text()
introduction = response.doc(".attraction_details > div").text()
return {
"name" : name,
"rating" : rating,
"address" : address,
"phone" : phone,
"introduction" : introduction,
"url": response.url,
"title": response.doc('title').text(),
}
這個利用的pyquery 。將頁面相應的內容全部抓下來。
最後是一些其他的操作了。如存入到數據庫,存入到文件中。
def on_result(self,result):
if result:
self.saveToFile(result)
def saveToFile(self,result):
file = open("/root/result.txt","a")
file.write(str(result)+"\n")
file.close()
這樣就存起來了。