Python發送post請求實例代碼
#!/usr/bin/python #-*-coding:utf-8-*- import httplib,urllib; #加載模塊 #定義需要進行發送的數據 params = urllib.urlencode({'title':'標題','content':'文章'}); #定義一些文件頭 headers = {"Content-Type":"application/x-www-form-urlencoded", "Connection":"Keep-Alive","Referer":"http:///sing/post.php"}; #與網站構建一個連接 conn = httplib.HTTPConnection("http:///sing/"); #開始進行數據提交 同時也可以使用get進行 conn.request(method="POST",url="post.php",body=params,headers=headers); #返回處理後的數據 response = conn.getresponse(); #判斷是否提交成功 if response.status == 302: print "發布成功!"; else: print "發布失敗"; #關閉連接 conn.close();<span id="more-998"></span> 不使用COOKIES 簡單提交 import urllib2, urllib data = {'name' : 'www', 'password' : '123456'} f = urllib2.urlopen( url = 'http:///', data = urllib.urlencode(data) ) print f.read() 使用COOKIES 復雜 import urllib2 cookies = urllib2.HTTPCookieProcessor() opener = urllib2.build_opener(cookies) f = opener.open('http:///?act=login&name=user01') data = '<root>Hello</root>' request = urllib2.Request( url = 'http:///?act=send', headers = {'Content-Type' : 'text/xml'}, data = data) opener.open(request)*