【问题标题】:How to check if request post has been successfully posted?如何检查请求帖子是否已成功发布?
【发布时间】:2017-03-28 14:07:24
【问题描述】:


我正在使用 python requests 模块来处理我正在抓取的特定网站上的请求。我对 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)

有什么方法可以检查数据是否已成功发布? .status_code 方法是检查它的好方法吗?

【问题讨论】:

    标签: python http module python-requests


    【解决方案1】:

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

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

    【讨论】:

    • 我明白了。有没有办法查看发布后发布了哪些数据?
    • 可以使用 print(result.text)
    【解决方案2】:

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

    if response.ok:
        # whatever
    

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

    【讨论】:

      【解决方案3】:

      我正在使用此代码:

      import json
      
      def post():
          return requests.post('http://httpbin.org/post', data={'x': 1, 'y': 2})
      
      def test_post(self):
          txt = post().text
          txt = json.loads(txt)
          return (txt.get("form") == {'y': '2', 'x': '1'})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 2017-07-09
        • 2023-02-11
        • 1970-01-01
        • 2021-09-13
        相关资源
        最近更新 更多