使用请求在Python中发布方法

时间:2013-03-17 14:05:36

标签: python html post request python-requests

我有简单的形式,接受文本并通过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;
?>

我编写了一个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

注意:从浏览器运行时,form和abc.php运行良好

1 个答案:

答案 0 :(得分:4)

要使用的正确参数是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)