首页 > 解决方案 > 如何修复此 python 代码中的 HTTP 错误 400?

问题描述

我正在尝试从 Facebook 删除帖子。不断返回 HTTP 错误 400。任何线索?

这是我的代码:

try:
    req=urllib.request.Request(url)
    with urllib.request.urlopen(req) as response:
        the_page=response.read()
    if response.getcode()==200:
        data=json.loads(response.read().decode('utf-8'))
        print(data)
except Exception as e:
        print(e)

错误如下:

>>> response=urllib.request.urlopen(req)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    response=urllib.request.urlopen(req)
  File "C:\Users\sknkuh10\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\sknkuh10\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open
    response = meth(req, response)
  File "C:\Users\sknkuh10\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Users\sknkuh10\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error
    return self._call_chain(*args)
  File "C:\Users\sknkuh10\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
    result = func(*args)
  File "C:\Users\sknkuh10\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request
>>> 

标签: pythonhttp

解决方案


您的代码应该可以正常工作。请参见下面的示例。

import urllib.request

try:
    req = urllib.request.Request(url="https://www.google.com")
    response = urllib.request.urlopen(req)

    status_code = response.getcode()
    print("returned {} status code".format(status_code))
    
    if status_code == 200:
        charset = response.info().get_content_charset()
        content = response.read().decode(charset)
    else:
       #do something
       pass
   
except Exception as e:
        print(e)

引用RFC

400 (Bad Request) 状态码表示服务器不能或不会处理请求,因为某些东西被认为是客户端错误(例如,格式错误的请求语法、无效的请求消息帧或欺骗性请求路由)。

因此,我会说错误依赖于您请求的 url。


推荐阅读