Python 如何解决这个错误???raise HTTPError(请求完整的url、代码、消息、hdrs、fp)HTTPError:禁止
我想编写一个程序,使用api从web上获取随机图像,然后使用tkinter显示,但每次都会出现此错误Python 如何解决这个错误???raise HTTPError(请求完整的url、代码、消息、hdrs、fp)HTTPError:禁止,python,api,tkinter,urllib,Python,Api,Tkinter,Urllib,我想编写一个程序,使用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, Ima
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_安全性或一些类似的服务器安全特性阻止了已知的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)
非常感谢,它修复了错误:)