scrapy簡介:
Scrapy是一個爲了爬取網站數據,提取結構性數據而編寫的應用框架。 其能夠應用在數據挖掘,信息處理或存儲歷史數據等一系列的程序中。
其最初是爲了頁面抓取 (更確切來講, 網絡抓取 )所設計的, 也能夠應用在獲取API所返回的數據(例如 Amazon Associates Web Services ) 或者通用的網絡爬蟲。Scrapy用途普遍,能夠用於數據挖掘、監測和自動化測試
一.基本使用
1. scrapy startproject 項目名稱
- 在當前目錄中建立中建立一個項目文件(相似於Django)
-cd 項目名稱 進入項目目錄
2. scrapy genspider [-t template] <name> <domain>
- 建立爬蟲應用
如:
scrapy gensipider -t basic oldboy oldboy.com
scrapy gensipider -t xmlfeed autohome autohome.com.cn
PS:
查看全部命令:scrapy gensipider -l
查看模板命令:scrapy gensipider -d 模板名稱
3. scrapy list
- 展現爬蟲應用列表
4. scrapy crawl 爬蟲應用名稱 --nolog
- 運行單獨爬蟲應用
-----------------------------------------------------
二.項目結構
project_name/
scrapy.cfg
project_name
/
__init__.py
items.py
pipelines.py
settings.py
spiders
/
__init__.py
爬蟲
1.py
爬蟲
2.py
爬蟲
3.py
-----------------------------------------------------------------------------------------------------css
三.xpath選擇器基本// 子子孫孫.// 當前子/ 兒子python
/div[@id="i1"] 兒子中div標籤切id爲i1
/div[@id="i1"]/text() 獲取某個標籤的文本
obj.extract() 列表中每一個字符串=》[]
obj.extract.first() 列表中每一個字符串=》列表第一個元素
運用url作選擇
// a[re:test(@href,"/all/hot/recent/\d+")]/@href
注:可在Chrome瀏覽器審查元素中,選中並copy xpath
css選擇器略...
------------------------------------------------------------------
四. scrapy shell
用法:scrapy shell www.baidu.com(domin)
優勢:調試做用域固定在domin上,調試個別代碼不用啓動整個框架,從而減小調試時間
五.經常使用函數
res = HtmlXpathSelector(response).select()shell
六.增長main,debug整框架瀏覽器
from scrapy.cmdline import execute import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) execute(["scrapy", "crawl", "chouti", "--nolog"])