Web Crawler:Scrapy
鄭鈞輿
sly22320660@gmail.com
Outline
 什麼是網路爬蟲?
 什麼是Scrapy?
 實作流程
 參考資料
什麼是網路爬蟲?
 A Web crawler is an Internet bot that systematically
browses the World Wide Web, typically for the purpose
of Web indexing. A Web crawler may also be called a Web
spider.(From wiki)
什麼是Scrapy?
 Scrapy 是一個網路爬行的框架,主要是用來爬網站以及擷取網站上資料。
 open-source
 Scrapy 是由Python所編寫而成
Architecture overview
Installation
 需要安裝:
python2.7
pip
lxml
openSSL
 接著安裝Scrapy:
$ pip install scrapy
或者
$ easy_install scrapy
需要的基礎
 Python的基本語法 (因為Scrapy是由python所編寫而成)
 Xpath的基本語法 ( http://www.w3schools.com/XPath )
(因為Scrapy使用xpath語法來找網頁的tag)
若想檢測xpath的抓取的tag的正確性,可以使用Scrapy shell實際去跑一次檢查。
至於scrapy shell 是python的interpreter
執行:
$ scrapy shell “<url>”
Xpath基本語法
實作流程
1.創建新的scrapy project
2.定義要擷取的Items
3.寫spider去爬網站以及擷取資料
4.寫pipeline去儲存和處理得到的資料
1.創建新的scrapy project
$ scrapy startproject <project_name>
scrapy.cfg: the project configuration file.
tutorial/:the project’s python module.
items.py: the project’s items file.
pipelines.py : the project’s pipelines file.
setting.py : the project’s setting file.
spiders/ : a directory where you’ll later put your spiders.
2.定義Items
範例:
ps: written in items.py
3.寫一個spider (最簡單的一種)
Ps:在/spiders裡自行創建spider.py
3.寫一個spider(最常使用的一種)
4.寫pipeline去處理資料(有特殊需求再寫)
 首先,在setting.py加上
ITEM_PIPELINES = [‘<your_project_name>.pipelines.<your_pipeline_classname>']
ex: ITEM_PIPELINES = ['AppleNewsCrawler.pipelines.ApplenewscrawlerPipeline']
 接著在pipelines.py中輸入
執行Spider
若有執行第四個步驟:
$ scrapy crawl <spider_name> ex: $ scrapy crawl yahoo
若沒有執行第四個步驟:
$ scrapy crawl <spider_name> -o items.json -t json
ex: $ scrapy crawl yahoo –o items.json –t json
最後輸出的json檔存在/spiders/items.json
參考資料
 1.Scrapy at a glance (主要)
http://doc.scrapy.org/en/latest/intro/overview.html
 2. w3schools xpath教學
http://www.w3schools.com/XPath
 3. Ubuntu下安裝scrapy
http://blog.csdn.net/chenguolinblog/article/details/19569059

Web crawler - Scrapy