Python 发送Post/GET请求

1 简单实现POST方法:

import urllib
import urllib2

data = {'username':'melon','password':'passwd','authcode':'1234'}
encoded_data = urllib.urlencode(data)
url='http://**.**.com/login/'
print urllib2.urlopen(url, encoded_data).read()

 2 POST详细实现,可以添加header头信息

import urllib
import urllib2

request = urllib2.Request('http://**.**.com/login/')
request.add_header( 
		'User-agent','Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'
		)
data = {'username':'melon','password':'passwd','authcode':'1234'}
encoded_data = urllib.urlencode(data)
request.add_data(encoded_data)
print urllib2.urlopen(request).read()

 注意:add_data()方法,每次调用都会替换上一次的数据

 

 3 GET方法

#!/usr/bin/env python
import urllib
import urllib2

login_data = {'name':'melon','password':'123456'}
login_url='http://login.*.com/login.php'
encoded_login_string = login_url+"?"+urllib.urlencode(login_data)
login_req = urllib2.Request(encoded_login_string)
m = urllib2.urlopen(login_req).read()
print m

 

你可能感兴趣的:(Python POST请求数据)