Python - 使用 Python 3 urllib 发出 POST 请求

Python - make a POST request using Python 3 urllib

我正在尝试向以下页面发出 POST 请求:http://search.cpsa.ca/PhysicianSearch

为了模拟单击 'Search' 按钮而不填写任何表单,这会将数据添加到页面。在 Chrome 开发人员工具中查看网络选项卡时,我通过单击按钮获得了 POST header 信息。我发布这个而不是仅仅复制其他类似问题的解决方案的原因是我相信我可能没有得到正确的 header 信息。

它的格式是否正确,我是否获取了正确的信息?我以前从未提出过 POST 请求。

这是我拼凑出来的:

import urllib.parse
import urllib.request


data = urllib.parse.urlencode({'Host': 'search.cpsa.ca', 'Connection': 'keep-alive', 'Content-Length': 23796,
                                     'Origin': 'http://search.cpsa.ca', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                                     'Cahce-Control': 'no-cache', 'X-Requested-With': 'XMLHttpRequest',
                                     'X-MicrosoftAjax': 'Delta=true', 'Accept': '*/*',
                                     'Referer': 'http://search.cpsa.ca/PhysicianSearch',
                                     'Accept-Encoding': 'gzip, deflate',
                                     'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6',
                                     'Cookie': 'ASP.NET_SessionId=kcwsgio3dchqjmyjtwue402c; _ga=GA1.2.412607756.1459536682; _gat=1'})


url = "http://www.musi-cal.com/cgi-bin/query?%s"

data = data.encode('ascii')
with urllib.request.urlopen("http://search.cpsa.ca/PhysicianSearch", data) as f:
    print(f.read().decode('utf-8'))

此解决方案输出页面的 HTML,但不包含我想从 POST 请求中检索的任何数据。

这就是你的做法。

from urllib import request, parse
data = parse.urlencode(<your data dict>).encode()
req =  request.Request(<your url>, data=data) # this will make the method "POST"
resp = request.urlopen(req)

谢谢C熊猫。你真的让我很容易学习这个模块。

我发布了我们传不给我编码的字典。我不得不做一个小改动 -

from urllib import request, parse
import json

# Data dict
data = { 'test1': 10, 'test2': 20 }

# Dict to Json
# Difference is { "test":10, "test2":20 }
data = json.dumps(data)

# Convert to String
data = str(data)

# Convert string to byte
data = data.encode('utf-8')

# Post Method is invoked if data != None
req =  request.Request(<your url>, data=data)

# Response
resp = request.urlopen(req)

上面的代码用一些额外的 \" 对 JSON 字符串进行了编码,这给我带来了很多问题。这看起来是一种更好的方法:

from urllib import request, parse

url = "http://www.example.com/page"

data = {'test1': 10, 'test2': 20}
data = parse.urlencode(data).encode()

req = request.Request(url, data=data)
response = request.urlopen(req)

print (response.read())

我使用urlencode时失败了。所以我使用以下代码在 Python3 中进行 POST 调用:

from urllib import request, parse

data = b'{"parameter1": "test1", "parameter2": "test2"}'
req = request.Request("http://www.musi-cal.com/cgi-bin/query?%s", data)
resp = request.urlopen(req).read().decode('utf-8')
print(resp)

request.Request()中设置method="POST"


发送一个没有正文的 POST 请求:

from urllib import request

req = request.Request('https://postman-echo.com/post', method="POST")
r = request.urlopen(req)
content = r.read()
print(content)

发送 POST 请求,正文为 json:

from urllib import request
import json

req = request.Request('https://postman-echo.com/post', method="POST")
req.add_header('Content-Type', 'application/json')
data = {
    "hello": "world"
}
data = json.dumps(data)
data = data.encode()
r = request.urlopen(req, data=data)
content = r.read()
print(content)