python中如何发post请求?


想用python发送post请求给网站,以便获取数据,请问该如何编写?

网络 开发 python

音无结弦D 9 years ago

借这个帖子GET和POST一起说了吧,代码很直接,用到了urllib2 和 urllib,请参考下列示例:

GET

import urllib2, urllib
data = urllib.urlopen('http://192.168.1.3test')

for line in data.readlines():
    print urllib2.urlopen("http://192.168.1.3/test?result="+line).read()

POST

import urllib2, urllib

url = 'http://192.168.1.3/test/'
data = urllib.urlencode({'login' : 'MyLogin', 'password' : 'MyPassword'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
d = response.read()
print d

url2 = "http://192.168.1.3/test?result="+str(d)
req2 = urllib2.Request(url2, data)
r2 = urllib2.urlopen(req2)
print r2.read()
因为瘦所以受 answered 9 years ago

Your Answer