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
4 使用request
import requests
url="http://localhost/testing/posting.php"
data= {
'subject': 'Alice-subject',
'message': 'alice-body',
'post': 'Submit',
}
cookies = {'phpbb2mysql_data': 'a%3A2%3A%7Bs%3A11%3A%22autologinid%22%3Bs%3A0%3A%22%22%3Bs%3A6%3A%22userid%22%3Bs%3A1%3A%223%22%3B%7D',
'phpbb2mysql_sid': '5b2e663a3d724cc873053e7ca0f59bd0',
}
#get方法
print requests.get(url, data=data, cookies=cookies).text
#post方法, data 可以是字符串等
print requests.post(url, data=data, cookies=cookies).text