Python:从url检索文件并生成数据:URI

时间:2016-03-03 12:58:42

标签: python url-encoding

我有一个关于gravatar图像的网址

url = "http://www.gravatar.com/avatar/0eee0fa5a325a984dab6c1e9c7a1968f?d=retro&s=40"

我想生成数据:它的URI就像下面的python

  

数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAIAAAADnC86AAAAjklEQVRYhWP0E3dnIAUY9jdiFT9fWE + SOUwkqaYiGHkWs + CSQI5LUuOPGL0jL6gHzGJGYvIxrryLCxCTJkZeUI9aPGoxzQDOshoXwJVHSc3rIy + oB0dZTa32FDHmjLygHnz5GDk + KKmPcekdeUE9OPIxMsDVNiYmj462qweVxUS1q2kBRl5Qj1o8ajHNAABQ3ieujBTqugAAAABJRU5ErkJggg ==

1 个答案:

答案 0 :(得分:1)

使用base64requests

import base64
import requests

url = "https://www.gravatar.com/avatar/0eee0fa5a325a984dab6c1e9c7a1968f?d=retro&s=40"
response = requests.get(url)
content_type = response.headers["content-type"]
encoded_body = base64.b64encode(response.content)
print("data:{};base64,{}".format(content_type, encoded_body.decode()))

响应:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAIAAAADnC86AAAAjklEQVRYhWP0E3dnIAUY9jdiFT9fWE+SOUwkqaYiGHkWs+CSQI5LUuOPGL0jL6gHzGJGYvIxrryLCxCTJkZeUI9aPGoxzQDOshoXwJVHSc3rIy+oB0dZTa32FDHmjLygHnz5GDk+KKmPcekdeUE9OPIxMsDVNiYmj462qweVxUS1q2kBRl5Qj1o8ajHNAABQ3ieujBTqugAAAABJRU5ErkJggg==