如何检查请求帖是否已成功发布?

Vic*_*now 2 python module http python-requests


我正在使用python请求模块来处理我正在抓取的特定网站上的请求.我对HTTP请求相当新,但我确实理解基础知识.这是情况.有一个我要提交的表单,我通过使用来自请求模块的post方法来实现:

# I create a session
Session = requests.Session()
# I get the page from witch I'm going to post the url
Session.get(url)
# I create a dictionary containing all the data to post
PostData = {
  'param1': 'data1',
  'param2': 'data2',
}
# I post
Session.post(SubmitURL, data=PostData)
Run Code Online (Sandbox Code Playgroud)

有没有办法检查数据是否已成功发布?.status_code方法是检查它的好方法吗?

小智 7

如果您从发布时获取结果,则可以检查状态代码:

result = Session.post(SubmitURL, data=PostData)
if result.status_code == requests.codes.ok:
    # All went well...
Run Code Online (Sandbox Code Playgroud)


aru*_*zca 7

我是Python新手,但我认为最简单的方法是:

if response.ok:
    # whatever
Run Code Online (Sandbox Code Playgroud)

因为所有 2XX 代码都是成功请求,而不仅仅是 200