PySpider
Begin
安裝pip install pyspider
在windows系統好像會出現如下問題
Command "python setup.py egg_info" failed with error code 10 in
解決方法:
利用wheel安裝
S1: pip install wheel
S2: 進入www.lfd.uci.edu/~gohlke/pythonlibs/,Ctrl + F查找pycurl
S3:
這個包名是pycurl-版本-你下載的python版本(如python3.4,就是cp34)-win32/64操作系統)
,選擇你所需要的進行下載
S4: 安裝編譯包,命令行輸入 pip install 你下載的whl文件的位置如(d:\pycurl-7.43.1-cp34-cp34m-win_amd64.whl)
S5: 繼續pip install pyspider
####Use
命令行輸入pyspider all
,啟動pyspider(啟動的時候可能一直卡在result_worker starting, 這個時候先等等, 然后再Ctrl + C關閉, 再次 pyspider all)
接着進入網站localhost:5000
,出現如下頁面
接着點擊Create,輸入項目名和你所要爬的網站
進入項目后左邊是視圖區,可以看很多東西;右邊是代碼編輯區
接着講講代碼使用
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-01-13 10:23:04
# Project: test
from pyspider.libs.base_handler import *
class Handler(BaseHandler):
crawl_config = {
}
@every(minutes=24 * 60)
def on_start(self):
self.crawl('https://scrapy.org/', callback=self.index_page)#這句代碼的意思是爬取'https://scrapy.org/',進入之后回調,觸發self.index_page函數,這個時候response就是獲取到的頁面
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
for each in response.doc('a[href^="http"]').items():#這里的response.doc語法使用的是jQuery的語法,獲取屬性href前綴為http的a標簽(這里使用的CSS選擇器語法)
self.crawl(each.attr.href, callback=self.detail_page)#接着爬取所有獲取到的a標簽鏈接,每訪問一個,觸發回調函數self.detail_page,這個時候的response就是訪問的當前網站的html頁面
@config(priority=2)
def detail_page(self, response):
#這里返回一個對象
return {
"url": response.url,
"title": response.doc('title').text(),
}
相關資料:
https://segmentfault.com/a/1190000002477863 這里三篇教程都很好,可以以它為實例,
http://www.pyspider.cn/book/pyspider/pyspider-Quickstart-2.html 當然還有必不可少的官方文檔!