Python:从Google下载图片

时间:2018-08-01 12:46:39

标签: python django google-api

我正在使用Google的Books API根据ISBN号获取有关图书的信息。我正在获取缩略图以及其他信息。响应如下所示:

 "imageLinks": {
 "smallThumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
 "thumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},

我想在上面的链接上下载缩略图,并将其存储在本地文件系统中。 python怎么办?

2 个答案:

答案 0 :(得分:1)

使用urllib模块

例如:

import urllib

d = {"imageLinks": {
     "smallThumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
     "thumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
     }
}

urllib.urlretrieve(d["imageLinks"]["thumbnail"], "MyThumbNail.jpg")

Python3X

from urllib import request

with open("MyThumbNail.jpg", "wb") as infile:
    infile.write(request.urlopen(d["imageLinks"]["thumbnail"]).read())

答案 1 :(得分:0)

将HTTP请求发送到相应的URL,然后获取content。然后将内容写入文件。

查看示例

imageLinks = {
    "smallThumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
    "thumbnail": "http://books.google.com/books/content?id=tEDhAAAAMAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
}
import requests

img = requests.get(imageLinks['thumbnail']).content
with open("myfile.jpg", 'wb') as img_file:
    img_file.write(img)