抓取cn.bing.com的每日图片

Posted on Posted in python
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8


"""
爬取微软的图片接口
"""
from contextlib import closing
import os, requests, json

storage_dir = '/路径/' # 图片存的路径,前后都有 / 符号
soft_imgs_api_url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN' # 微软图片接口

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"} # agent

soft_imgs_api_url_res = requests.get(soft_imgs_api_url, headers = headers) # 获取接口数据,返回类型是bytes
soft_imgs_api_url_res_dict = json.loads(soft_imgs_api_url_res.content.decode('utf-8')) # bytes 转成字典
soft_img_url = soft_imgs_api_url_res_dict['images'][0]['url'] # 获取图片url
soft_img_url_pre = soft_img_url.split('.')[-1] # 获取图片类型 jpg/png/jpeg
soft_img_url = 'https://cn.bing.com' + soft_img_url # 拼接完整的图片url
soft_img_url_name = soft_img_url.split('/')[-1] # 截取图片名字

with closing (requests.get(soft_img_url, headers = headers, stream = True)) as response: # 以流的形式,down imgs
    with open(storage_dir + soft_img_url_name , 'wb') as fd:
        for chunk in response.iter_content(128):
            fd.write(chunk)
» 转载请注明来源:若我若鱼 » 抓取cn.bing.com的每日图片

Leave a Reply

Your email address will not be published. Required fields are marked *

two + eight =