Scrapy爬虫实战------360摄影美图

网站:

http://images.so.com/

切换到摄影界面。

打开开发者工具:

我们在下拉的时候可以看到这是一个ajax请求,数据结构是json。

sn=30返回的是前30张图片,sn=60返回的是30到60的图片。

创建项目:

构造请求:

url为:http://images.so.com/zj?ch=photography&listtype=new&sn=30&listtype=new

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

提取信息:

首先要定义一个Item:

from scrapy import Item,Field

class Images360Item(Item):
    #MongoDb存储的collection名称和mysql的表名称
    collection = table = 'images'
    id = Field()
    url = Field()
    title = Field()
    thumb = Field()

提取Spider的信息:

from ..items import Images360Item
import json
def parse(self, response):
    # print(response)
    result = json.loads(response.text)

    for image in result.get('list'):
        item = Images360Item()
        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

存储信息

pipelines.py文件中

Mongo存储

class 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):
        """存入数据"""
        self.db[item.collection].insert(dict(item))
        return item

    def close(self,item,spider):
        """关闭数据库"""
        self.client.close()

Mysql存储:

class MysqlPipeline():
    def __init__(self, host, database, user, password, port):
        self.host = host
        self.database = database
        self.user = user
        self.password = password
        self.port = port

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            host=crawler.settings.get('MYSQL_HOST'),
            database=crawler.settings.get('MYSQL_DATABASE'),
            user=crawler.settings.get('MYSQL_USER'),
            password=crawler.settings.get('MYSQL_PASSWORD'),
            port=crawler.settings.get('MYSQL_PORT'),
        )

    def open_spider(self, spider):
        self.db = pymysql.connect(self.host, self.user, self.password, self.database, charset='utf8',
                                  port=self.port)
        self.cursor = self.db.cursor()

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

    def process_item(self, item, spider):
        
        data = dict(item)
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        sql = 'insert into %s (%s) values (%s)' % (item.table, keys, values)
        self.cursor.execute(sql, tuple(data.values()))
        self.db.commit()
        return item

然后下载图片,代码如下:

class ImagePipeline(ImagesPipeline):
    def file_path(self, request, response=None, info=None):
        # 获取下载路径
        url = request.url
        print('******************')
        print(url)
        # 命名
        file_name = url.split('/')[-1]
        return file_name

    def item_completed(self, results, item, info):
        # results对应下载结果,是一个列表形式
        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):
        #将url字段拿出来,执行下载。
        yield Request(item['url'])

然后在settings.py文件中添加下载路径:

IMAGES_STORE = './images'

启用管道文件:

ITEM_PIPELINES = {
    'images360.pipelines.ImagePipeline': 300,
    'images360.pipelines.MongoPipeline': 301,
    'images360.pipelines.MysqlPipeline': 302,

}

数据库配置的设置:

MONGO_URI = 'localhost'
MONGO_DB = 'images360'
MYSQL_HOST = 'localhost'
MYSQL_DATABASE = 'images360'
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_PASSWORD = '123456'

最后保存的结果如下:

Mongo:

Mysql:

注意:最后几项的配置一定不能出错,不然或是产生存储不了的结果,或是图片无法下载的结果。

猜你喜欢

转载自blog.csdn.net/qq_39138295/article/details/83867423
今日推荐