如何使用 Python 将 HTTP POST 值发送到 (PHP) 页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/629518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:30:03  来源:igfitidea点击:

How do I send a HTTP POST value to a (PHP) page using Python?

phppythonpost

提问by Hank Gay

I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks!

我有一个 PHP 页面,它有 1 个文本框,当我按下提交按钮时。我的 SQL 将把这个产品名称存储到我的数据库中。我的问题是;是否可以使用要求 1 个值的 Python 脚本发送/发布产品名称,然后使用我的 PHP 页面将其发送到我的数据库?谢谢!

回答by kkubasik

Check out the urllib and urllib2 modules.

查看 urllib 和 urllib2 模块。

http://docs.python.org/library/urllib2.html

http://docs.python.org/library/urllib2.html

http://docs.python.org/library/urllib.html

http://docs.python.org/library/urllib.html

Simply create a Request object with the needed data. Then read the response from your PHP service.

只需使用所需的数据创建一个 Request 对象。然后读取来自您的 PHP 服务的响应。

http://docs.python.org/library/urllib2.html#urllib2.Request

http://docs.python.org/library/urllib2.html#urllib2.Request

回答by Jerub

When testing, or automating websites using python, I enjoy using twill. Twill is a tool that automatically handles cookies and can read HTML forms and submit them.

在使用 python 测试或自动化网站时,我喜欢使用 twill。Twill 是一种自动处理 cookie 的工具,可以读取 HTML 表单并提交它们。

For instance, if you had a form on a webpage you could conceivably use the following code:

例如,如果您在网页上有一个表单,您可以想象使用以下代码:

from twill import commands
commands.go('http://example.com/create_product')
commands.formvalue('formname', 'product', 'new value')
commands.submit()

This would load the form, fill in the value, and submit it.

这将加载表单,填写值并提交。

回答by skyronic

I find http://www.voidspace.org.uk/python/articles/urllib2.shtmlto be a good source of information about urllib2, which is probably the best tool for the job.

我发现http://www.voidspace.org.uk/python/articles/urllib2.shtml是有关 urllib2 的良好信息来源,它可能是完成这项工作的最佳工具。

import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

The encoding is actually done using urllib, and this supports HTTP POST. There is also a way to use GET, where you have to pass the data into urlencode.

编码实际上是使用 urllib 完成的,它支持 HTTP POST。还有一种使用 GET 的方法,您必须将数据传递到 urlencode 中。

Don't forget to call read() though, otherwise the request won't be completed.

但是不要忘记调用 read() ,否则请求将不会完成。

回答by Hank Gay

Yes. urllib2is a nice Python way to form/send HTTP requests.

是的。urllib2是一种很好的 Python 方式来形成/发送 HTTP 请求。

回答by FredWe

Personally i prefer to use Requests. As its summary, this is a HTTP library for Python, built for human beings.

我个人更喜欢使用Requests。总之,这是一个PythonHTTP 库,为人类构建

To quickly solve problems, rather than study deeply in HTTP, Requestswill be a better choice. (Yeah, i mean compared to urllibor socket)

为了快速解决问题,与其深入研究 HTTP,Requests会是更好的选择。(是的,我的意思是与urllibsocket相比)

For example, A python file which send a POST request with userdata:

例如,发送带有用户数据的 POST 请求的 python 文件:

import requests
userdata = {"firstname": "Smith", "lastname": "Ayasaki", "password": "123456"}
resp = requests.post('http://example.com/test.php', data = userdata)

And the following text.php treating this request:

下面的 text.php 处理这个请求:

$firstname = htmlspecialchars($_POST["firstname"]);
$lastname = htmlspecialchars($_POST["lastname"]);
$password = htmlspecialchars($_POST["password"]);
echo "FIRSTNAME: $firstname  LASTNAME: $lastname  PW: $password";

Finally, the response text (resp.content in python) will be like:

最后,响应文本(python 中的 resp.content)将类似于:

FIRSTNAME: Smith LASTNAME: Ayasaki PW: 123456

名字:Smith 姓氏:Ayasaki 密码:123456

回答by cdleary

Just an addendum to @antileet's procedure, it works similarly if you're trying to do a HTTP POST request with a web-service-like payload, except you just omit the urlencode step; i.e.

只是@antileet程序的一个附录,如果您尝试使用类似 Web 服务的有效负载执行 HTTP POST 请求,它的工作方式类似,只是省略了 urlencode 步骤;IE

import urllib, urllib2

payload = """
<?xml version='1.0'?>
<web_service_request>
    <short_order>Spam</short_order>
    <short_order>Eggs</short_order>
</web_service_request>
""".strip()
query_string_values = {'test': 1}
uri = 'http://example.com'

# You can still encode values in the query string, even though
# it's a POST request. Nice to have this when your payload is
# a chunk of text.
if query_string_values:
    uri = ''.join([uri, '/?', urllib.urlencode(query_string_values)])
req = urllib2.Request(uri, data=payload)
assert req.get_method() == 'POST'
response = urllib2.urlopen(req)
print 'Response:', response.read()