当前位置:   article > 正文

python使用urlopen/urlretrieve下载文件时出现403 forbidden的解决方法【转载】_urllib.error.urlerror:

urllib.error.urlerror:

第一:urlopen出现403

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import urllib
  4. url = "http://www.google.com/translate_a/t?client=t&sl=zh-CN&tl=en&q=%E7%94%B7%E5%AD%A9"
  5. #浏览器头
  6. headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
  7. req = urllib2.Request(url=url,headers=headers)
  8. data = urllib.request.urlopen(req).read()
  9. print data

二:urlretrieve 出现403(转载自:https://www.213.name/archives/1087/comment-page-1

出现该错误的原因是服务器开启了反爬虫,一般情况下只需要设置header模拟浏览器即可,但是urlretrieve并未提供header参数。

使用urlopen也可以直接下载文件,例

  1. 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"}
  2. def down_pic(url, path):
  3. try:
  4. req = request.Request(url, headers=headers)
  5. data = request.urlopen(req).read()
  6. with open(path, 'wb') as f:
  7. f.write(data)
  8. f.close()
  9. except Exception as e:
  10. print(str(e))

还有一种解决方法:

  1. opener=urllib.request.build_opener()
  2. 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')]
  3. urllib.request.install_opener(opener)
  4. urllib.request.urlretrieve(url, Path)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/912884
推荐阅读
相关标签