Python "HTTP Error 403: Forbidden"

Posted 软件测试杂谈

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python "HTTP Error 403: Forbidden"相关的知识,希望对你有一定的参考价值。

问题:

执行下面的语句时

1 def set_IPlsit():
2     url = https://www.whatismyip.com/
3     response = urllib.request.urlopen(url)
4     html = response.read().decode(utf-8)

出现以下异常:

 

C:\Users\54353\AppData\Local\Programs\Python\Python36\python.exe "C:/Users/54353/PycharmProjects/untitled/爬虫/图片 - 某网站.py"
Traceback (most recent call last):
  File "C:/Users/54353/PycharmProjects/untitled/爬虫/图片 - 某网站.py", line 100, in <module>
    ip = set_IPlsit2()
  File "C:/Users/54353/PycharmProjects/untitled/爬虫/图片 - 某网站.py", line 95, in set_IPlsit2
    response = ure.urlopen(url)
  File "C:\Users\54353\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\54353\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\Users\54353\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response
    http, request, response, code, msg, hdrs)
  File "C:\Users\54353\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\Users\54353\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Users\54353\AppData\Local\Programs\Python\Python36\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

Process finished with exit code 1

 

分析:

出现上面的异常是因为用 urllib.request.urlopen 方式打开一个URL,服务器端只会收到一个单纯的对于该页面访问的请求,但是服务器并不知道发送这个请求使用的浏览器,操作系统,硬件平台等信息,而缺失这些信息的请求往往都是非正常的访问,例如爬虫。

有些网站为了防止这种非正常的访问,会验证请求信息中的UserAgent,如果UserAgent存在异常或者是不存在,那么这次请求将会被拒绝。

 

解决方法:

在请求中添加UserAgent,代码如下

1 headers = {User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0}  
2 req = urllib.request.Request(url=chaper_url, headers=headers)  
3 urllib.request.urlopen(req).read()  

 

以上是关于Python "HTTP Error 403: Forbidden"的主要内容,如果未能解决你的问题,请参考以下文章

Python安装python包时遇到"error: Microsoft Visual C++ 9.0 is required"的简答

python urllib2导出elasticsearch数据时 返回 "urllib2.HTTPError: HTTP Error 500: Internal Server Error&q

python异常处理时报错,提示:HTTPError: HTTP Error 404: Not Found

Error: Can't find Python executable "python", you can set the PYTHON env variable.解决办法

python2.7升级到python3后,用pip进行安装时报Fatal error in launcher:Unbale to create process using`""(示

sqli-lab 第一题 单引号 error based single quotes