Python模仿POST提交HTTP数据及使用Cookie值的方法
本文实例讲述了在Python中模仿POSTHTTP数据及带Cookie提交数据的实现方法,分享给大家供大家参考。具体实现方法如下:
方法一
如果不使用Cookie,发送HTTPPOST非常简单:
importurllib2,urllib data={'name':'www','password':'123456'} f=urllib2.urlopen( url ='https://www.nhooo.com/', data =urllib.urlencode(data) ) printf.read()
当使用Cookie时,代码变得有些复杂:
importurllib2 cookies=urllib2.HTTPCookieProcessor() opener=urllib2.build_opener(cookies) f=opener.open('http://www.xxxx.net/?act=login&name=user01') data='<root>Hello</root>' request=urllib2.Request( url ='http://www.xxxx.net/?act=send', headers={'Content-Type':'text/xml'}, data =data) opener.open(request)
第一次open()是进行登录.服务器返回的Cookie被自动保存在cookies中,被用在后来的请求.
第二次open()用POST方法向服务器发送了Content-Type=text/xml的数据.如果你不创建一个Request,而是直接使用urlopen()方法,Python强制把Content-Type改为application/x-www-form-urlencoded.
方法二
用urllib2库,带Cookie请求URL页面
例1:
importurllib2 opener=urllib2.build_opener() opener.addheaders.append(('Cookie','cookiename=cookievalue')) f=opener.open("http://example.com/")
例2:
importurllib2 importurllib fromcookielibimportCookieJar cj=CookieJar() opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) #input-typevaluesfromthehtmlform formdata={"username":username,"password":password,"form-id":"1234"} data_encoded=urllib.urlencode(formdata) response=opener.open("https://page.com/login.php",data_encoded) content=response.read()
希望本文所述对大家的Python程序设计有所帮助。