我尝试使用 Python 编写一个简短的批量下载脚本,用来将图片列表存储到本地。
它对于 http
图片的 url 工作得非常好,但是对于任何带有 https
的 url 却无法下载。涉及到问题的代码行如下:
import urllib.request
urllib.request.urlretrieve(url, filename)
例如,
https://cdn.discordapp.com/attachments/299398003486097412/303580387786096641/FB_IMG_1490534565948.jpg
会导致HTTP Error 403: Forbidden
,以及任何其他https
图像。
这让我有两个问题:
- 我如何使用Python下载这样的图像?
- 为什么图像甚至有
https
URL,如果它们基本上只是文件?
编辑:
以下是堆栈跟踪:
Traceback (most recent call last):
File "img_down.py", line 52, in <module>
main()
File "img_down.py", line 38, in main
save_img(d, l)
File "img_down.py", line 49, in save_img
stream = read_img(url)
File "img_down.py", line 42, in read_img
with urllib.request.urlopen(url) as response:
File "D:\Users\Jan\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "D:\Users\Jan\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 532, in open
response = meth(req, response)
File "D:\Users\Jan\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "D:\Users\Jan\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 570, in error
return self._call_chain(*args)
File "D:\Users\Jan\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)
File "D:\Users\Jan\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden