Problems & Solutions -- HTTPError: Forbidden
程序员文章站
2022-07-08 14:45:37
...
前两天遇到了这个报错:HTTPError: Forbidden
排除了其他可能出错的代码块,发现是下载图片那几行代码出了问题
在Stack Overflow 上找到了解决方法。
In [3]: img_url = 'http://mm.howkuai.com/wp-content/uploads/2017a/04/18/01.jpg'
...:
...:
...:
In [4]: path = 'F:\\pic_test\\test.jpg'
In [5]: from urllib.request import urlretrieve
In [6]: urlretrieve(img_url,path)
Traceback (most recent call last):
File "<ipython-input-6-75d384725ac0>", line 1, in <module>
urlretrieve(img_url,path)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 248, in urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 532, in open
response = meth(req, response)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 570, in error
return self._call_chain(*args)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)
File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
HTTPError: Forbidden
解决方案:
In [7]: import urllib.request
In [8]: opener=urllib.request.build_opener()
In [9]: opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36')]
In [10]: urllib.request.install_opener(opener)
In [11]: path = 'F:\\pic_test\\test.jpg'
In [12]: img_url = 'http://mm.howkuai.com/wp-content/uploads/2017a/04/18/01.jpg'
In [13]: urlretrieve(img_url,path)
Out[14]: ('F:\\pic_test\\test.jpg', <http.client.HTTPMessage at 0x7ca94f0>)
F盘的pic_test文件夹下出现了下载好的图片:
推荐阅读
-
Problems & Solutions -- 6. MySql 中文乱码问题
-
solutions&reflection Array problems 1313,
-
Problems & Solutions -- HTTPError: Forbidden
-
urllib2.HTTPError: HTTP Error 403: Forbidden 分类: ...
-
urllib2.HTTPError: HTTP Error 403: Forbidden
-
urllib2.HTTPError: HTTP Error 403: Forbidden
-
网络爬虫urllib.error.HTTPError: HTTP Error 403: Forbidden的问题方法
-
urllib.error.HTTPError: HTTP Error 403: Forbidden 解决办法
-
使用python爬取图片写入文件夹,附urllib.error.HTTPError: HTTP Error 403: Forbidden问题解决
-
python3.3 urllib.error.HTTPError: HTTP Error 403: Forbidden