【问题标题】:How can I convert this Curl call into Python 3?如何将此 Curl 调用转换为 Python 3?
【发布时间】:2020-02-03 02:53:34
【问题描述】:

我有以下 curl 成功将我登录到网站。它返回一个 302 和一个 cookie:

curl \
--verbose \
--request POST \
--data '__EVENTTARGET=&body%3Ax%3AtxtLogin=kingkong%40mailinator.com&body%3Ax%3AbtnLogin=&crypted_pass=736015615f9e251692a6a4aa8a7baa14' \
"https://emma.maryland.gov/page.aspx/en/usr/login"

不幸的是,我必须插入帐户的真实用户名和加密密码。否则这个 curl 它不会工作。 但是,这是一个完全虚拟的帐户,其中没有任何私人数据。 所以请不要生我的气。

我想使用requests.post() 将其转换为 Python3 代码。所以我做了这个代码:

>>> requests.post(
...     url='https://emma.maryland.gov/page.aspx/en/usr/login',
...     data={
...         '__EVENTTARGET': '',
...         'body:x:txtLogin': 'kingkong@mailinator.com',
...         'body:x:btnLogin': '',
...         'crypted_pass': '736015615f9e251692a6a4aa8a7baa14'
...     }
... )
<Response [200]>

但是我从 Python3 代码 (200) 得到的响应与我从 Curl (302) 得到的响应不匹配。这意味着目标服务器感知到两个请求之间的差异。

如何将 curl 转换为发送完全相同的底层 HTTP 请求的 Python3?

【问题讨论】:

    标签: python python-3.x curl python-requests


    【解决方案1】:

    您的requests 代码实际上比cURL 命令更智能。

    HTTP 302 - 是一个重定向,cURL 没有跟随它并给你它得到的第一个响应。您可以使用 -L 使 cURL 跟随重定向:Is there a way to follow redirects with command line cURL?

    requests 代码跟随重定向并为您提供最终响应,恰好是 HTTP 200。

    用-L 试试你的 curl 命令,看看你是否获得了 HTTP 200。

    或者,您可以使用allow_redirects=False 选项要求requests 不遵循重定向:Is there an easy way to request a URL in python and NOT follow redirects?

    【讨论】:

    • Curl -L 不跟随。它仍然给出 302。但是添加 allow_redirects=False 通过使我的 python 返回 302 来解决我的问题。这就是我想要的。我不想遵循重定向。谢谢!
    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多