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

我正在尝试向以下页面发出POST请求:http :

//search.cpsa.ca/PhysicianSearch

为了模拟单击“搜索”按钮而不填写任何表单,该表单会将数据添加到页面。通过在chrome开发人员工具中查看“网络”标签时点击按钮,我获得了POST标头信息。我之所以发布此信息,而不是仅仅从其他类似问题中复制解决方案,是因为我认为我可能没有获得正确的标题信息。格式是否正确,我是否掌握了正确的信息?我以前从未提出过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)

以上是 Python-使用Python 3 urllib发出POST请求 的全部内容, 来源链接: utcz.com/qa/402353.html

回到顶部