官方網址:。
安裝指令:pip install Scrapy
## 安裝完成,使用預設範本新建一個項目,指令:scrapy startproject xx
## 上圖很形象的說明了,scrapy的運作機制。具體各部分的意義和作用,可自行百度,這裡不再贅述。我們一般,需要做的是以下步驟。 1)設定settings,其他設定可依自己的要求檢視文件配置。
DEFAULT_REQUEST_HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.10 Safari/537.36'} DOWNLOAD_TIMEOUT = 30IMAGES_STORE = 'Images'
class CnblogImageItem(scrapy.Item): image = scrapy.Field() imagePath = scrapy.Field() name = scrapy.Field()
class GaoxiaoSpiderMiddleware(object):def process_request(self, request, spider):if len(request.flags) > 0 and request.flags[0] == 'img':return None driver = webdriver.PhantomJS()# 设置全屏 driver.maximize_window() driver.get(request.url) content = driver.page_source driver.quit()return HtmlResponse(request.url, encoding='utf-8', body=content)class ProxyMiddleWare(object):def process_request(self, request, spider): request.meta['proxy'] = 'http://175.155.24.103:808'
class CnblogImagesPipeline(ImagesPipeline): IMAGES_STORE = get_project_settings().get("IMAGES_STORE")def get_media_requests(self, item, info): image_url = item['image']if image_url != '':yield scrapy.Request(str(image_url), flags=['img'])def item_completed(self, result, item, info): image_path = [x["path"] for ok, x in result if ok]if image_path:# 重命名if item['name'] != None and item['name'] != '': ext = os.path.splitext(image_path[0])[1] os.rename(self.IMAGES_STORE + '/' + image_path[0], self.IMAGES_STORE + '/' + item['name'] + ext) item["imagePath"] = image_pathelse: item['imagePath'] = ''return item
# coding=utf-8import sysimport scrapyimport gaoxiao.itemsimport json reload(sys) sys.setdefaultencoding('utf-8')class doubanSpider(scrapy.Spider): name = 'douban'allowed_domains = ['movie.douban.com'] baseUrl = ''start = 0 start_urls = [baseUrl + str(start)] custom_settings = {'DOWNLOADER_MIDDLEWARES': {'gaoxiao.middlewares.ProxyMiddleWare': 1,# 'gaoxiao.middlewares.GaoxiaoSpiderMiddleware': 544 },'ITEM_PIPELINES': {'gaoxiao.pipelines.CnblogImagesPipeline': 1, } }def parse(self, response): data = json.loads(response.text)['subjects']for i in data: item = gaoxiao.items.CnblogImageItem()if i['cover'] != '': item['image'] = i['cover'] item['name'] = i['title']else: item['image'] = ''yield itemif self.start < 400: self.start += 20yield scrapy.Request(self.baseUrl + str(self.start), callback=self.parse)
以上是豆瓣影片圖片爬取實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!