Ideal

早就发现Unsplash上的照片都好美,非常适合做图片,最近有空查了下发现Unsplash有提供api,于是我就搞了个Python脚本下这些图片,另外申请的是dev用途的api key,所以每个小时只能调用100次。
API
=====
API文档 https://unsplash.com/developers
url: https://api.unsplash.com/photos?page=1&client_id=YOUR_CLIENT_ID
返回json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
[
{
"id": "qIwFIwxl3CI",
"created_at": "2016-05-25T08:18:13-04:00",
"width": 6000,
"height": 4000,
"color": "#C4CDF8",
"likes": 26,
"liked_by_user": false,
"user": {
"id": "EE_nXdS9eDA",
"username": "jtc",
"name": "Jesse Collins",
"profile_image": {
"small": "https://images.unsplash.com/profile-fb-1449247869-60cdce9ffdf3.jpg?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=32&w=32&s=8d80b1b60af1d736d4caa2c30405596c",
"medium": "https://images.unsplash.com/profile-fb-1449247869-60cdce9ffdf3.jpg?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=64&w=64&s=600eda7460fba39075a8a36c365f74f8",
"large": "https://images.unsplash.com/profile-fb-1449247869-60cdce9ffdf3.jpg?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=128&w=128&s=747513014baac7b141d9509c3aadc0e0"
},
"links": {
"self": "https://api.unsplash.com/users/jtc",
"html": "http://unsplash.com/@jtc",
"photos": "https://api.unsplash.com/users/jtc/photos",
"likes": "https://api.unsplash.com/users/jtc/likes"
}
},
"current_user_collections": [],
"urls": {
"raw": "https://images.unsplash.com/photo-1464178634217-fdda7ccaf33d",
"full": "https://images.unsplash.com/photo-1464178634217-fdda7ccaf33d?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=2906d37810fa60db2d199a5af81e96de",
"regular": "https://images.unsplash.com/photo-1464178634217-fdda7ccaf33d?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&w=1080&fit=max&s=539ca882797c062051d5d614c991aa0e",
"small": "https://images.unsplash.com/photo-1464178634217-fdda7ccaf33d?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&w=400&fit=max&s=e6ed2cb890f9c17bfca0e77602cd4f4f",
"thumb": "https://images.unsplash.com/photo-1464178634217-fdda7ccaf33d?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&w=200&fit=max&s=c4e4f1017e7f4ec0b1446258e058ae2d"
},
"categories": [
{
"id": 4,
"title": "Nature",
"photo_count": 45678,
"links": {
"self": "https://api.unsplash.com/categories/4",
"photos": "https://api.unsplash.com/categories/4/photos"
}
}
]
...
]

可以看到,我们能通过urls提供的连接选择所需要的不同大小的照片。另外可以改变url参数page翻页,默认一页是10张照片。
Python
======

  1. 使用requests得到图片的url
    1
    2
    3
    payload = {'client_id': 'YOUR CLIENT_ID'
    ,'page':page_num}
    r = requests.get('https://api.unsplash.com/photos', params = payload)
  2. 通过urllib2下载图片
    1
    imgData = urllib2.urlopen(pic_url).read()
  3. 写入文件
    1
    2
    3
    4
    5
    6
    7
    if not os.path.exists(fileName):
    output = open(fileName,'wb+')
    output.write(imgData)
    output.close()
    print("Finished download " + pic_id)
    else:
    print("path not exists")
    代码我已经上传github了:https://github.com/brucewzp/fetchingUnsplashPhotos