出现该错误的原因是服务器开启了反爬虫,一般情况下只需要设置header模拟浏览器即可,但是urlretrieve并未提供header参数。
使用urlopen也可以直接下载文件,例
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"} def down_pic(url, path): try: req = request.Request(url, headers=headers) data = request.urlopen(req).read() with open(path, 'wb') as f: f.write(data) f.close() except Exception as e: print(str(e))
还有一种解决方法:
opener=urllib.request.build_opener() opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')] urllib.request.install_opener(opener) urllib.request.urlretrieve(url, Path)
转载自: