我想编写一个程序,使用 api 从 web 获取随机图像,然后使用 tkinter 显示它,但每次我得到这个错误
raise HTTPError(req.full_url, code, msg, hdrs, fp
HTTPError: Forbidden)
当我使用其他图像链接时,此代码有效!为什么 ?我该如何解决这个错误?
import requests
import io
# allows for image formats other than gif
from PIL import Image, ImageTk
import tkinter as tk
# Python3
from urllib.request import urlopen
root = tk.Tk()
url = "https://api.thecatapi.com/v1/images/search"
response = requests.get(url)
r=response.json()
URL=r[0]["url"]
image_bytes = urlopen(URL).read()
# internal data file
data_stream = io.BytesIO(image_bytes)
# open as a PIL image object
pil_image = Image.open(data_stream)
# optionally show image info
# get the size of the image
w, h = pil_image.size
# split off image file name
fname = URL.split('/')[-1]
sf = "{} ({}x{})".format(fname, w, h)
root.title(sf)
# convert PIL image object to Tkinter PhotoImage object
tk_image = ImageTk.PhotoImage(pil_image)
# put the image on a typical widget
label = tk.Label(root, image=tk_image, bg='brown')
label.pack(padx=5, pady=5)
root.mainloop()
```