python urllib发送post请求,Python - 使用Python 3 urllib发出POST请求

I am trying to make a POST request to the following page:http://search.cpsa.ca/PhysicianSearch

In order to simulate clicking the 'Search' button without filling out any of the form, which adds data to the page. I got the POST header information by clicking on the button while looking at the network tab in chrome developer tools. The reason I'm posting this instead of just copying solutions from the other similar problems is that I believe I may have not gotten the correct header information. Is it properly formatted and did I grab the right information? I've never made a POST request before.

This is what I've managed to piece together:

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'))

This solution outputs the page's HTML, but not with any of the data I wanted to retrieve from the POST request.

解决方案

This is how you do it.

from urllib import request, parse

data = parse.urlencode().encode()

req = request.Request(, data=data) # this will make the method "POST"

resp = request.urlopen(req)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值