问题 HTTP 错误 403:从 Internet 读取时被禁止 [重复]
Posted
技术标签:
【中文标题】问题 HTTP 错误 403:从 Internet 读取时被禁止 [重复]【英文标题】:Problem HTTP Error 403: Forbidden when reading from the internet [duplicate] 【发布时间】:2021-09-18 10:54:52 【问题描述】:我试图从互联网上读取图像,但我不断收到 HTTP 错误 403:禁止访问。我查看了Problem HTTP Error 403 page,但此页面对我没有帮助。 这是我的代码:
import cv2
import urllib.request`
import numpy as np
req = urllib.request.urlopen('https://media.discordapp.net/attachments/862441786333200394/862449591642488882/pokemon.png?width=473&height=473')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'
cv2.imshow(img)
这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\Auto Typer\AT TEST2.py", line 15, in <module>
req = urllib.request.urlopen('https://media.discordapp.net/attachments/862441786333200394/862449591642488882/pokemon.png?width=473&height=473')
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
response = meth(req, response)
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
response = self.parent.error(
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
return self._call_chain(*args)
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
result = func(*args)
File "C:\Users\User1\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
【问题讨论】:
这能回答你的问题吗? Problem HTTP error 403 in Python 3 Web Scraping 【参考方案1】:将User-Agent
标头添加到您的请求中:
req = urllib.request.urlopen('https://media.discordapp.net/attachments/862441786333200394/862449591642488882/pokemon.png?width=473&height=473', headers='User-Agent': 'Mozilla/5.0')
它大概知道你是一个机器人,所以为了安全而阻止你。
【讨论】:
以上是关于问题 HTTP 错误 403:从 Internet 读取时被禁止 [重复]的主要内容,如果未能解决你的问题,请参考以下文章