How to solve this Error ??? raise HTTPError(req.full_url, code, msg, hdrs, fp) HTTPError: Forbidden
How to solve this Error ??? raise HTTPError(req.full_url, code, msg, hdrs, fp) HTTPError: Forbidden
我想编写一个程序,使用 api 从网络上获取随机图像,然后使用 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()
```
这是因为 mod_security 或某些类似的服务器安全功能阻止了已知的 spider/bot 用户代理(urllib 使用类似 python urllib/3.3.0,它是容易被发现)。尝试设置一个已知的浏览器用户代理:
headers={'User-Agent': 'Mozilla/5.0'}
完整代码
import urllib.request
req = urllib.request.Request(url="http://localhost/",
headers=headers={'User-Agent': 'Mozilla/5.0'}
handler = urllib.request.urlopen(req)
我想编写一个程序,使用 api 从网络上获取随机图像,然后使用 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()
```
这是因为 mod_security 或某些类似的服务器安全功能阻止了已知的 spider/bot 用户代理(urllib 使用类似 python urllib/3.3.0,它是容易被发现)。尝试设置一个已知的浏览器用户代理:
headers={'User-Agent': 'Mozilla/5.0'}
完整代码
import urllib.request
req = urllib.request.Request(url="http://localhost/",
headers=headers={'User-Agent': 'Mozilla/5.0'}
handler = urllib.request.urlopen(req)