參考資料:
Scrapy中文文檔 http://scrapy-chs.readthedocs.io/zh_CN/stable/index.html
Scrapy研究探索系列 http://blog.csdn.net/u012150179/article/details/32343635
scrapy使用相較于之前的urllib和requests兩個爬蟲庫的使用還是要復雜很多,感覺一些簡單的爬蟲直接用requests+BeautifulSoup來的更簡單更快,為什么不用urllib?又是decode又是encode的挺麻煩,而requests則簡單了許多.而scrapy學會了之后使用起來感覺也比requests簡單方便些,難點是對于一些網(wǎng)站反爬蟲的解決方案,現(xiàn)在這方面還是學的很差,接下來以一個例子簡單了解記錄下學習過程,具體scrapy學習還請參考上面給出的參考資料以及Google吧.
1. 創(chuàng)建爬蟲項目
scrapy startproject collectips #創(chuàng)建一個爬取http://www.xicidaili.com/nn/上面代理ip的項目
創(chuàng)建項目后會自動生成一個目錄,大致如下,其中ips.csv是最后爬取的ip存儲的文件,一開始是沒有的
├── collectips
├── collectips
│ ├── __init__.py
│ ├── items.py #設置要爬取的項目的內(nèi)容部分
│ ├── middlewares.py #中間部件
│ ├── pipelines.py #對生成的item進行處理,若不設置,則默認為原網(wǎng)頁爬取到的內(nèi)容
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ ├── items.cpython-35.pyc
│ │ └── settings.cpython-35.pyc
│ ├── settings.py #每個項目都有這個文件,可對爬蟲進行相關(guān)設置,如cookies,User-Agent等
│ └── spiders #編寫爬蟲主代碼,此文件下可編寫多個爬蟲
│ ├── __init__.py
│ ├── ips.csv #這是最后生成的文件,創(chuàng)建項目時是沒有的
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ └── xici.cpython-35.pyc
│ └── xici.py #編寫爬蟲代碼的文件,非自動生成
└── scrapy.cfg
2. 編輯items.py文件,填入想要爬取內(nèi)容的名稱
# -*- 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 CollectipsItem(scrapy.Item):
IP = scrapy.Field() #要爬取的代理ip
PORT = scrapy.Field() #ip端口
DNS_POSITION = scrapy.Field() #服務器地址
TYPE = scrapy.Field() #ip類型,http或者https
SPEED = scrapy.Field() #ip響應速度
LAST_CHECK_TIME = scrapy.Field() #ip最后更新時間
3. 編寫主要爬蟲
編寫爬蟲時可使用默認模板來生成爬蟲文件,命令行命令為scrapy genspider [options] <name> <domain>
# -*- coding: utf-8 -*-
import scrapy
from collectips.items import CollectipsItem
from scrapy.selector import Selector
class XiciSpider(scrapy.Spider):
name = "xici" #爬蟲名稱
allowed_domains = ["http://www.xicidaili.com"] #允許爬取的范圍
#重寫start_requests()函數(shù),生成多個要爬取的頁面
def start_requests(self):
reqs = []
for i in range(1, 21):
req = scrapy.Request(
'http://www.xicidaili.com/nn/{}'.format(i))
reqs.append(req)
return reqs
#編寫parse()函數(shù)對爬取的網(wǎng)頁內(nèi)容進行分析,提取出想要的部分
def parse(self, response):
item = CollectipsItem()
sel = Selector(response)
#使用xpath選擇器來選取我們想要的網(wǎng)頁標簽內(nèi)容
for i in range(2, 102):
item['IP'] = sel.xpath(
'//*[@id="ip_list"]/tr[{}]/td[2]/text()'.format(i)).extract_first()
item['PORT'] = sel.xpath(
'//*[@id="ip_list"]/tr[{}]/td[3]/text()'.format(i)).extract_first()
item['DNS_POSITION'] = sel.xpath(
'//*[@id="ip_list"]/tr[{}]/td[4]/a/text()'.format(i)).extract_first()
item['TYPE'] = sel.xpath(
'//*[@id="ip_list"]/tr[{}]/td[6]/text()'.format(i)).extract_first()
item['SPEED'] = sel.xpath(
'//*[@id="ip_list"]/tr[{}]/td[7]/div/@title'.format(i)).extract_first()
item['LAST_CHECK_TIME'] = sel.xpath(
'//*[@id="ip_list"]/tr[{}]/td[10]/text()'.format(i)).extract_first()
yield item
編寫爬蟲提取標簽時可采用scrapy自帶的shell工具進行調(diào)試,命令行命令為scrapy shell 'website'
,若爬取成功,則會返回一個類似ipython的工具,可使用response.headers來查看返回的headers,采用response.xpath('//some/path/title/text()')
來調(diào)試提取的內(nèi)容
4. 防止爬蟲被ban的一些方法
- 更改設置文件settings.py,禁止cookies
- 延長爬取間隔時間delay
- 使用多個User-Agent
- 使用代理ip
5. 使用chrome插件xpath helper快速獲取目的內(nèi)容的標簽
使用xpath方法獲取目的內(nèi)容標簽時,有點地方瀏覽器會對源html進行更改,加入一個tbody標簽,如果我們使用的xpath標簽中含有tbody,將無法獲取正確內(nèi)容,需要手動刪除tbody這個標簽.
xpath helper能幫助我們快速獲得目的內(nèi)容的標簽,方便提取.使用方法為:打開目的網(wǎng)頁后,Ctrl+shift+X調(diào)出xpath helper的控制臺,將鼠標移至任何目的內(nèi)容位置,按下shift鍵即可在控制臺中查看鼠標所在內(nèi)容的標簽以及其內(nèi)容.