python - 如何修复此 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
>>>
解决方案
您的代码应该可以正常工作。请参见下面的示例。
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。
推荐阅读
- c# - 返回具有分配的所有子项的新列表的函数 VS 返回该列表的子项但未分配的函数
- google-cloud-platform - 如何将 Cloud Endpoints 配置到现有的 Spring Boot 应用程序(在 App Engine 上运行)?
- java - 使用 Part 类 jsp 编译 FileUpload servlet 时找不到符号
- scala - Spark 提交作业在本地模式下失败且没有错误
- database - 尝试将 csv 文件中的数据插入 accdb 表时出现问题
- csv - 使用胶水将巨大的 CSV 转换为带有分区的 Parquet
- mysql - MySQL慢查询日志空提交
- c# - unity 字符跳跃和下降超过我输入的值
- git - 暂时禁用 github Webhook
- cypress - 用于类似数组的 prevSubject 的赛普拉斯自定义命令