国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python3爬蟲爬取英雄聯盟高清桌面壁紙功能示例【基于Scrapy框架】

2020-02-15 23:57:20
字體:
來源:轉載
供稿:網友

本文實例講述了Python3爬蟲爬取英雄聯盟高清桌面壁紙功能。分享給大家供大家參考,具體如下:

使用Scrapy爬蟲抓取英雄聯盟高清桌面壁紙

源碼地址:https://github.com/snowyme/loldesk

開始項目前需要安裝python3和Scrapy,不會的自行百度,這里就不具體介紹了

首先,創建項目

scrapy startproject loldesk

生成項目的目錄結構

首先需要定義抓取元素,在item.py中,我們這個項目用到了圖片名和鏈接

import scrapyclass LoldeskItem(scrapy.Item):  name = scrapy.Field()  ImgUrl = scrapy.Field()  pass

接下來在爬蟲目錄創建爬蟲文件,并編寫主要代碼,loldesk.py

import scrapyfrom loldesk.items import LoldeskItemclass loldeskpiderSpider(scrapy.Spider):  name = "loldesk"  allowed_domains = ["www.win4000.com"]  # 抓取鏈接  start_urls = [    'http://www.win4000.com/zt/lol.html'  ]  def parse(self, response):    list = response.css(".Left_bar ul li")    for img in list:      imgurl = img.css("a::attr(href)").extract_first()      imgurl2 = str(imgurl)      next_url = response.css(".next::attr(href)").extract_first()      if next_url is not None:        # 下一頁        yield response.follow(next_url, callback=self.parse)      yield scrapy.Request(imgurl2, callback=self.content)  def content(self, response):    item = LoldeskItem()    item['name'] = response.css(".pic-large::attr(title)").extract_first()    item['ImgUrl'] = response.css(".pic-large::attr(src)").extract()    yield item    # 判斷頁碼    next_url = response.css(".pic-next-img a::attr(href)").extract_first()    allnum = response.css(".ptitle em::text").extract_first()    thisnum = next_url[-6:-5]    if int(allnum) > int(thisnum):      # 下一頁      yield response.follow(next_url, callback=self.content)

圖片的鏈接和名稱已經獲取到了,接下來需要使用圖片通道下載圖片并保存到本地,pipelines.py:

from scrapy.pipelines.images import ImagesPipelinefrom scrapy.exceptions import DropItemfrom scrapy.http import Requestimport reclass MyImagesPipeline(ImagesPipeline):  def get_media_requests(self, item, info):    for image_url in item['ImgUrl']:      yield Request(image_url,meta={'item':item['name']})  def file_path(self, request, response=None, info=None):    name = request.meta['item']    name = re.sub(r'[?//*|“<>:/()0123456789]', '', name)    image_guid = request.url.split('/')[-1]    filename = u'full/{0}/{1}'.format(name, image_guid)    return filename  def item_completed(self, results, item, info):    image_path = [x['path'] for ok, x in results if ok]    if not image_path:      raise DropItem('Item contains no images')    item['image_paths'] = image_path    return item

最后在settings.py中設置存儲目錄并開啟通道:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 楚雄市| 连南| 育儿| 弋阳县| 舟山市| 翁源县| 读书| 卓尼县| 白沙| 珠海市| 河曲县| 右玉县| 玉溪市| 星子县| 翁牛特旗| 凤城市| 朝阳区| 新民市| 焦作市| 铜梁县| 蒲城县| 田林县| 巩留县| 上犹县| 启东市| 抚松县| 永丰县| 资溪县| 平陆县| 雷州市| 延庆县| 嘉兴市| 乐山市| 锡林郭勒盟| 霍山县| 抚宁县| 安宁市| 腾冲县| 长丰县| 三亚市| 松江区|