Reputation: 135
I want to write a program that gets random images from the web using the api and then displays it using tkinter, but every time I get this error
raise HTTPError(req.full_url, code, msg, hdrs, fp
HTTPError: Forbidden)
this code works when I use other image links! WHY ? How can I fix this error ??
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()
```
Upvotes: 5
Views: 8200
Reputation: 189
This is because of the mod_security or some similar server security feature that blocks known spider/bot user agents (urllib uses something like python urllib/3.3.0, it's easily detected). Try setting a known browser user agent with:
headers={'User-Agent': 'Mozilla/5.0'}
Full Code
import urllib.request
req = urllib.request.Request(url="http://localhost/",
headers=headers={'User-Agent': 'Mozilla/5.0'}
handler = urllib.request.urlopen(req)
Upvotes: 3