【问题标题】:Post method in Python using requestsPython 中使用请求的 Post 方法
【发布时间】:2013-03-19 12:44:04
【问题描述】:

我有一个简单的表单,它接受文本并通过 post 方法调用一个 php 文件 abc.php:

<form method='post' action="abc.php">
<input type="textarea" name="text">
<input type="submit">
</form>

abc.php 的内容

<?php
$msg=$_POST["text"];
print $msg;
?>

我使用 requests 库编写了一个用于发布消息的 python 脚本,如下所示:

import requests
keys={'text':'lol rofl'}
r=requests.post("http://127.0.0.1/abc.php/POST",params=keys)
print r.url
print r.text

我得到以下输出(错误):

  http://localhost/abc.php/POST?text=lol+rofl

<b>notice</b>:undefined index;text in C:/xampp/htdocs/abc.php on line 2

note:form 和 abc.php 在浏览器运行时完美运行

【问题讨论】:

    标签: python html post request python-requests


    【解决方案1】:

    正确使用的参数是data:

    http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests

    Typically, you want to send some form-encoded data — much like an HTML form.
    To do this, simply pass a dictionary to the data argument.
    Your dictionary of data will automatically be form-encoded
    when the request is made:
    
    >>> payload = {'key1': 'value1', 'key2': 'value2'}
    >>> r = requests.post("http://httpbin.org/post", data=payload)
    

    【讨论】:

    • @btevfik:这是一个.get()(GET 请求)调用。对于 POST,请使用 data
    • 为什么它们会让它们与众不同
    • @btevfik 因为 GET 参数与 POST 数据完全不同? POST 请求可以选择指定 GET 参数以及 POST 数据,尽管 GET 请求显然不能指定 POST 数据。它们是不同的东西,在不同的情况下使用。
    猜你喜欢
    • 2023-04-02
    • 2015-07-02
    • 2017-03-07
    • 2019-07-28
    • 2017-10-02
    • 2014-12-09
    • 1970-01-01
    相关资源
    最近更新 更多