參考官方文檔:http://scrapy-chs.readthedocs.io/zh_CN/1.0/intro/tutorial.html#spider 學習筆記
安裝
安裝分別在ubunut
和MAC
系統下安裝,過程如下:
ubuntu
系統:
# 使用pip安裝Scrapy
sudo pip install Scrapy
# 遇到報錯,報哪個包沒有,就是用pip安裝哪個
MAC
系統:
# 先確保已經安裝 xcode
xcode-select --install
# 使用 pip 安裝 Scrapy
sudo pip install Scrapy
# 遇到報錯 關于six-1.4.1的,無法升級到新的版本。如下兩種解決辦法:
1、 sudo pip install scrapy --ignore-installed six # 跳過
2、 sudo easy_install "six>=1.5.2" # 使用easy_install 升級six。然后安裝
創建項目:
$ scrapy startproject tutorial # 創建項目
$ cd tutorial/ ; tree # 進入到目錄,并展示目錄結構
.
├── scrapy.cfg
└── tutorial
├── __init__.py
├── items.py # 保存爬去到的數據的容器,繼承 scrapy.Item 類
├── pipelines.py
├── settings.py
└── spiders
└── __init__.py
└── dmoz_spider.py # 該文件為自己創建,繼承 scrapy.Spider 類。定義屬性:
# name(唯一,區別spider)
# start_urls(spider啟動時進行爬去的列表,第一個被獲取到
的頁面將是其中之一。 后續的URL則從初始的URL獲取到的數據中提
?。? # pasrse() 方法,被調用時,每個初始URL完成下載后生成的
Response 對象將會作為唯一的參數傳遞給該函數。 該方法負責解
析返回的數據(response data),提取數據(生成item)以及生成
需要進一步處理的URL的 Request 對象。
編寫第一個爬蟲
目的:獲取url頁面源碼。(并未用到上邊定義的Items
)
創建一個spider
,繼承scrapy.Spider
類,并定義一些屬性:
-
name:
用于區別Spider
。 該名字必須是唯一的,不可以為不同的Spider
設定相同的名字。 -
start_urls:
包含了Spider
在啟動時進行爬取的url
列表。 因此,第一個被獲取到的頁面將是其中之一。 后續的URL
則從初始的URL
獲取到的數據中提取 -
parse():
是spider
的一個方法。 被調用時,每個初始URL
完成下載后生成的Response(頁面內容)
對象將會作為唯一的參數傳遞給該函數。 該方法負責解析返回的數據(response data),提取數據(生成item
)以及生成需要進一步處理的URL
的Request
對象。
在tutorial/spiders
目錄中創建dmoz_spider.py
,如下:
#coding=utf-8
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allow_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
#----- 從start_urls中讀取頁面源碼信息,并寫入本地---#
def parse(self,response):
# reponse.body 會輸出請求url的源碼,response.url 是所請求的 url 地址
# 通過下面的輸出語句發現,start_urls 中的url地址的請求結果被分別帶入到該方法中。
print "debug---------"
print response.body
print response.url
print "debug----------"
# 過濾出請求 url 地址的最后一段,并以該段的名字來創建文件,并寫入對應的網頁源碼。
filename = response.url.split("/")[-2] + '.html'
with open(filename,"wb") as f:
f.write(response.body)
執行:
進入項目的根目錄,執行下列命令啟動spider
$ scrapy crawl dmoz
執行結果:在項目目錄下,會生成兩個文件,Books.html
和Resources.html
,文件內容分別是兩個url頁面的源碼。
編寫第二個項目(從選定的url地址中提取我們想要的信息)
定義Item
Item
是保存爬取到的數據的容器。其使用方法和字典類似,雖然可以在Scrapy
中直接使用dict
,但是Item
提供了額外保護機制來避免拼寫錯誤導致的未定義字段錯誤。
編輯tutorial
目錄中的items.py
文件,根據我們需要獲取到的數據對item
進行建模。下邊分別定義了title
、url
和網站的描述。
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TutorialItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
通過開發者工具對頁面的源碼進行分析,我們要提取的信息如下:
在tutorial/spiders
目錄中創建dmoz_spider.py
,如下:
#coding=utf-8
import scrapy
from tutorial.items import DmozItem
class DmozSpider(scrapy.Spider):
name = "dmoz"
allow_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
# ----- 從start_urls中的頁面源碼中提取自己需要的,title、link、簡介
def parse(self, response):
for sel in response.xpath('//*[@class="title-and-desc"]'):
# item 對象是自定義的 python 字典,可以使用標準的字典語法來獲取到每個段子的值,字段就是之前在items.py文件中用Field賦值的屬性。
item = DmozItem()
item['title'] = sel.xpath('a/div/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('div/text()').extract()
yield item
執行:
進入項目的根目錄,執行下列命令啟動spider
$ scrapy crawl dmoz
在輸出的debug
信息中,可以看到生成的items
列表。更直觀一點可以將items
寫入文件:
$ scrapy crawl dmoz -o items.json -t josn
# -o 指定文件名稱 -t 指定格式
查看items.json
內容:
$ cat items.json | head -n 5
[
{"title": ["eff-bot's Daily Python URL "], "link": ["http://www.pythonware.com/daily/"], "desc": ["\r\n\t\t\t\r\n Contains links to assorted resources from the Python universe, compiled by PythonWare.\r\n ", "\r\n "]},
{"title": ["O'Reilly Python Center "], "link": ["http://oreilly.com/python/"], "desc": ["\r\n\t\t\t\r\n Features Python books, resources, news and articles.\r\n ", "\r\n "]},
{"title": ["Python Developer's Guide "], "link": ["https://www.python.org/dev/"], "desc": ["\r\n\t\t\t\r\n Resources for reporting bugs, accessing the Python source tree with CVS and taking part in the development of Python.\r\n ", "\r\n "]},
{"title": ["Social Bug "], "link": ["http://win32com.goermezer.de/"], "desc": ["\r\n\t\t\t\r\n Scripts, examples and news about Python programming for the Windows platform.\r\n ", "\r\n "]}
追蹤鏈接項目
上邊兩個項目,url
地址都是直接給出,現在需要將一個頁面中的url
地址提取出來,并依次進行處理。
取http://www.dmoz.org/Computers/Programming/Languages/Python/
中Related categories
部分的url
地址。如圖:
更改tutorial/items.py
文件,加入fromurl
,來表明這個信息來自哪個鏈接。如下:
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class DmozItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
fromurl = scrapy.Field()
在tutorial/spiders
目錄中創建dmoz_spider.py
,如下:
#coding=utf-8
import scrapy
from tutorial.items import DmozItem
class DmozSpider(scrapy.Spider):
name = "dmoz"
allow_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/"
]
# ----- 追蹤鏈接----#
def parse(self, response):
# 提取需要爬取的鏈接,產生(yield)一個請求, 該請求使用 parse_dir_contents() 方法作為回調函數, 用于最終產生我們想要的數據.。
print response.url
for link in response.xpath('//div[@class="see-also-row"]/a/@href'):
url = response.urljoin(link.extract())
yield scrapy.Request(url,callback=self.parse_dir_contents)
def parse_dir_contents(self,response):
# 提取信息,放入item中。這邊增加了一個fromurl,所以在items.py 文件中,也要加入。
for sel in response.xpath('//*[@class="title-and-desc"]'):
item = DmozItem()
item['title'] = sel.xpath('a/div/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['fromurl'] = response.url
item['desc'] = sel.xpath('div/text()').extract()
yield item
執行:
進入項目的根目錄,執行下列命令啟動spider
$ scrapy crawl dmoz -o items1.json -t josn
查看items1.json
內容:
cat items2.json | head -n 5
[
{"link": ["http://en.wikipedia.org/wiki/Bytecode"], "title": ["Bytecode "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Interpreted/Bytecode/", "desc": ["\r\n\t\t\t\r\n Growing article, with links to many related topics. [Wikipedia, open content, GNU FDL]\r\n ", "\r\n "]},
{"link": ["http://www.parrotcode.org/"], "title": ["Parrotcode "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Interpreted/Bytecode/", "desc": ["\r\n\t\t\t\r\n Home of Parrot Virtual Machine, made for dynamic languages, originally a target for Perl 6 compiler, hosts many language implementations in varied stages of completion: Tcl, Javascript, Ruby, Lua, Scheme, PHP, Python, Perl 6, APL, .NET. Open source.\r\n ", "\r\n "]},
{"link": ["http://vvm.lip6.fr/"], "title": ["Virtual Virtual Machine "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Interpreted/Bytecode/", "desc": ["\r\n\t\t\t\r\n VVM overview, history, members, projects, realizations, publications.\r\n ", "\r\n "]},
{"link": ["http://os.inf.tu-dresden.de/L4/l3elan.html"], "title": ["ELAN "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Multiparadigm/", "desc": ["\r\n\t\t\t\r\n Created 1974 by Technical University of Berlin group, as alternative to BASIC in teaching, for systematic programming, and related styles: top-down, bottom-up, recursive, modular, syntax-directed. Descriptions, brief resource list, documents. English, Deutsch.\r\n ", "\r\n "]},