我正在尝试从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
>>>
答案 0 :(得分:0)
您的代码应该可以正常工作。请参见下面的示例。
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(错误请求)状态代码表示服务器无法执行以下操作: 由于某些原因而不会处理请求 客户端错误(例如格式错误的请求语法,无效的请求) 邮件框架或欺骗性请求路由)。
因此,我想说的是错误取决于您的请求的网址。
答案 1 :(得分:0)
当您的请求中的某些内容与服务器的预期不符时,会发生此类错误。例如,可能是由于
Content-Type
标头?通常,API调用是application/json
或application/x-www-form-urlencoded
,但是还有其他可能。GET
,请确保API期望GET,而不是POST
或PUT
请求。GET
,但是如果您要发送POST
或PUT
,则您发送的数据中的错误可能导致服务器中出现400错误。Copy as Curl
。我发现顺便使用requests模块。