热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python爬取360摄影美图

爬取360摄影美图新建项目scrapy startproject images360创建一个Spiderscrapy genspider image image.so.com构造请求:爬取50页,每页


爬取360摄影美图

新建项目

scrapy startproject images360

创建一个Spider

scrapy genspider image image.so.com

构造请求:

爬取50页,每页30张,先在settings.py里定义一个MAX_PAGE,添加定义 MAX_PAGE = 50

定义 start_requests

def start_requests(self):
data = {'ch': 'photography', 'listtype': 'new'}
base_url = 'https://image.so.com/zj?'
for page in range(1, self.settings.get('MAX_PAGE') + 1):
data['sn'] = page * 30
params = urlencode(data)
url = base_url + params
yield Request(url, self.parse)

修改settings.py中ROBOTSTXT_OBEY变量,将其设置为False。

ROBOTSTXT_OBEY = False

提取信息:

from scrapy import Item, Field
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
class ImageItem(Item):
collection = 'images'

id = Field()
url = Field()
title = Field()
thumb = Field()

图片ID,链接,标题,缩略图

提取有关信息

def parse(self, response):
result = json.loads(response.text)
for image in result.get('list'):
item = ImageItem()
item['id'] = image.get('imageid')
item['url'] = image.get('qhimg_url')
item['title'] = image.get('group_title')
item['thumb'] = image.get('qhimg_thumb_url')
yield item

解析json,遍历其list,取出图片信息,对ImageItem赋值,生成Item对象。

存储信息

import pymongoclass MongoPipeline(object):
def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db

@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DB')
)

def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]

def process_item(self, item, spider):
name = item.collection
self.db[name].insert(dict(item))
return item

def close_spider(self, spider):
self.client.close()

settings.py里设置

MONGO_URI = ‘localhost’

MONGO_DB = ‘images360’

ImagePipeline

from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
class ImagePipeline(ImagesPipeline):
def file_path(self, request, respOnse=None, info=None):
url = request.url
file_name = url.split('/')[-1]
return file_name

def item_completed(self, results, item, info):
image_paths = [x['path'] for ok, x in results if ok]
if not image_paths:
raise DropItem('Image Downloaded Failed')
return item

def get_media_requests(self, item, info):
yield Request(item['url'])


推荐阅读
author-avatar
很呆很傻很天真2010_545
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有