在用Python的urllib和BeautifulSoup寫過了不少爬蟲以後,本人決定嘗試著名的Python爬蟲框架——Scrapy. 本次分享將詳細講述如何利用Scrapy來下載豆瓣電影Top250, 主要解決的問題有:python
首先咱們要爬取的豆瓣電影Top250網頁截圖以下:git
<center>  </center>   網頁的結構並不複雜,因此,咱們決定把全部的250部電影的圖片都下載下來。接下來,就開始咱們的Scrapy之旅啦~~   首先咱們新建一個Scrapy項目,叫作doubanMovie.github
scrapy startproject doubanMovie
該項目的文件樹形結構以下:web
<center>  </center>瀏覽器
修改items.py以下:微信
# -*- coding: utf-8 -*- import scrapy class DoubanmovieItem(scrapy.Item): # two items: url and name of image url = scrapy.Field() img_name = scrapy.Field()
這是咱們用來存放圖片的url和name的部分。app
接着,在spiders文件夾下,新建爬蟲(Spider)文件:doubanMovieSpider.py, 文件代碼以下:框架
import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from doubanMovie.items import DoubanmovieItem class movieSpider(Spider): # name of Spider name = "movie" #start urls start_urls = ["https://movie.douban.com/top250"] for i in range(1,10): start_urls.append("https://movie.douban.com/top250?start=%d&filter="%(25*i)) #parse function def parse(self, response): item = DoubanmovieItem() sel = Selector(response) images = sel.xpath('//*[@id="content"]/div/div[1]/ol/li') item['url'] = [] item['img_name'] = [] # append the url and name of the image in item for image in images: # extract url and name of the image site = image.xpath('div/div[1]/a/img/@src').extract_first() img_name = image.xpath('div/div[1]/a/img/@alt').extract_first() item['url'].append(site) item['img_name'].append(img_name) yield item
該部分代碼主要利用xpath來提出網頁中的電影圖片的url和name,並添加到item中。 爲了可以對下載後的圖片進行重命名,咱們須要修改pipeline.py文件,代碼以下:scrapy
# -*- coding: utf-8 -*- from scrapy.pipelines.images import ImagesPipeline from scrapy.http import Request class DoubanmoviePipeline(object): def process_item(self, item, spider): return item class MyImagesPipeline(ImagesPipeline): # yield meta for file_path() function def get_media_requests(self, item, info): for url in item['url']: yield Request(url, meta={'item': item, 'index':item['url'].index(url)}) # rename the image def file_path(self, request, response=None, info=None): item = request.meta['item'] index = request.meta['index'] image_name = item['img_name'][index] return 'full/%s.jpg' % (image_name)
在這兒咱們添加了MyImagesPipeline類,主要目的是用來對下載後的圖片進行重命名。 最後一步,也是關鍵的一步,就是修改settings.py文件,將其中的ROBOTSTXT_OBEY設置爲False, 這是爲了防止爬蟲被禁,而且添加如下代碼:ide
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0" ITEM_PIPELINES {'doubanMovie.pipelines.DoubanmoviePipeline': 2, 'doubanMovie.pipelines.MyImagesPipeline':1 } IMAGES_URLS_FIELD = 'url' IMAGES_STORE = r'.'
在上面的代碼中,咱們設置了USER_AGENT, 這是爲了在Linux系統中模擬瀏覽器的設置,讀者能夠根據本身的系統和瀏覽器來設置不一樣的USER_AGENT. 同時, 咱們又加了ITEM_PIPELINES管道和圖片的保存路徑。
一切就緒,咱們就能夠運行爬蟲啦。切換到spiders文件夾下,輸入scrapy list能夠查看爬蟲的名字,輸入scrapy crawl movie便可運行爬蟲。
<center>  </center>   movie爬蟲的運行結果以下: <center>  </center> 該爬蟲下載了250個文件,用時約13秒,效率驚人啊!   下載後的圖片保存在當前文件夾(spiders)下的full文件夾下,咱們來看一下里面的內容: <center>  </center>   Surprise!Wonderful! 裏面有沒有你喜歡的電影呢?
本項目的Github地址爲 https://github.com/percent4/doubanMovieSpider, 歡迎你們訪問哦~~
***注意:***本人現已開通兩個微信公衆號: 由於Python(微信號爲:python_math)以及輕鬆學會Python爬蟲(微信號爲:easy_web_scrape), 歡迎你們關注哦~~