一、scrapy的安裝:
本文基於Anacoda3,
Anacoda2和3如何同時安裝?
將Anacoda3安裝在C:\ProgramData\Anaconda2\envs文件夾中即可。
如何用conda安裝scrapy?
安裝了Anaconda2和3后,

如圖,只有一個命令框,可以看到打開的時候:

可以切到Anaconda3對應的路徑下即可。
安裝的方法:cmd中:conda install scrapy即可。
當然,可能會出現權限的問題,那是因為安裝的文件夾禁止了讀寫。可以如圖:

將權限都設為“允許“。
注意:此時雖然scapy安裝上了,但是在cmd中輸入scapy可能會不認,可以將安裝scrapy.exe的路徑添加到環境變量中。
二、scapy的簡單使用
例子:爬取圖片
1、 創建scrapy工程
譬如,想要創建工程名:testImage
輸入:scrapy startproject testImage
即可創建該工程,按照cmd中提示的依次輸入:
cd testImage
scrapy genspider getPhoto www.27270.com/word/dongwushijie/2013/4850.html
其中:在當前項目中創建spider,這僅僅是創建spider的一種快捷方法,該方法可以使用提前定義好的模板來生成spider,后面的網址是一個采集網址的集合,即為允許訪問域名的一個判斷。注意不要加http/https。
至此,可以在testImage\testImage\spiders中找到創建好的爬蟲getPhoto.py,可以在此基礎上進行修改。
2、創建爬蟲

如圖,可以在圖片的位置右鍵,檢查,查看源碼,在圖片所在的位置處,將xpath拷貝出來。
此時,可以找出圖片的地址:
class GetphotoSpider(scrapy.Spider):
name = 'getPhoto'
allowed_domains = ['www.27270.com']
start_urls = ['http://www.27270.com/word/dongwushijie/2013/4850.html']
def parse(self, response):
urlImage = response.xpath('//*[@id="picBody"]/p/a[1]/img/@src').extract()
print(urlImage)
pass
此時,注意網絡路徑的正確書寫,最后沒有/,
http://www.27270.com/word/dongwushijie/2013/4850.html/
此時將4850.html 當作了目錄,會出現404找不到路徑的錯誤!
3、 下載圖片
items.py:
class PhotoItem(scrapy.Item):
name = scrapy.Field()
imageLink = scrapy.Field()
pipelines.py:
from scrapy.pipelines.images import ImagesPipeline
import scrapy
class ImagePipeline(ImagesPipeline):
def get_media_requests(self,item,info):
image_link = item['imageLink']
yield scrapy.Request(image_link)
settings.py:
IMAGES_STORE = r"C:\Users\24630\Desktop\test"
另外,對於上面的網址,還需要ROBOTSTXT_OBEY = False
並且,訪問該網址會出現302錯誤,這是一個重定向的問題,
MEDIA_ALLOW_REDIRECTS =True
設置該選項,就可以正確下載,但是下載的還是不對,問題不好解決。
當然在爬蟲中,還要對items賦值:
from testImage import items
。。。
for urllink in urlImage:
item = items.PhotoItem()
item['imageLink'] = urllink
三、 進一步爬取(讀取下一頁)
# -*- coding: utf-8 -*-
import scrapy
from testImage import items
class GetphotoSpider(scrapy.Spider):
name = 'getPhoto'
allowed_domains = ['www.wmpic.me']
start_urls = ['http://www.wmpic.me/93912']
def parse(self, response):
#//*[@id="content"]/div[1]/p/a[2]/img
urlImage = response.xpath('//*[@id="content"]/div[1]/p/a/img/@src').extract()
print(urlImage)
for urllink in urlImage:
item = items.PhotoItem()
item['imageLink'] = urllink
yield item
ifnext = response.xpath('//*[@id="content"]/div[2]/text()').extract()[0]
# 當沒有下一篇,即最后一頁停止爬取
if("下一篇" in ifnext):
nextUrl = response.xpath('//*[@id="content"]/div[2]/a/@href').extract()[0]
url=response.urljoin(nextUrl)
yield scrapy.Request(url=url)
此時,便可以看到路徑下的下載后的文件了。(由於該網址每頁的圖片所在的xpath都不一樣,故下載的圖片不全)
