【Python3網頁post登陸】
阿新 • • 發佈:2017-05-26
__name__ firefox pin form mozilla tro index type 輸入
[引入庫]
import urllib import urllib.parse import urllib.request import http.cookiejar
[請求頭,通過FireFox查得]
headers = { ‘Accept‘: ‘text/html, application/xhtml+xml, image/jxr, */*‘, ‘Referer‘: ‘http://jxpt.cuit.edu.cn/eol/homepage/common/index.jsp‘, ‘Accept-Language‘: ‘zh-CN‘, ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko‘, ‘Content-Type‘: ‘application/x-www-form-urlencoded‘, ‘Accept-Encoding‘: ‘gzip, deflate‘, ‘Content-Length‘: 57, ‘Host‘: ‘jxpt.cuit.edu.cn‘, ‘Connection‘: ‘Keep-Alive‘, ‘Pragma‘: ‘no-cache‘, }
[需要post的數據]
postData = { ‘IPT_LOGINUSERNAME‘: ‘賬號‘, ‘IPT_LOGINPASSWORD‘: ‘密碼‘, }
[獲取cookie]
#輸入賬號密碼的地址 loginURL = ‘http://jxpt.cuit.edu.cn/eol/homepage/common/index.jsp‘ #自動記住cookie cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) urllib.request.install_opener(opener)# 安裝opener到全局 resp = urllib.request.urlopen(loginURL)
[post登陸]
#post數據地址 postURL = ‘http://jxpt.cuit.edu.cn/eol/homepage/common/login.jsp‘ #數據編碼 postData = urllib.parse.urlencode(postData).encode(‘utf-8‘) #構造請求 request = urllib.request.Request(postURL, postData, headers) #發送請求 response = urllib.request.urlopen(request)
[打印返回的信息]
#respInfo = response.info() #接收返回的信息 html = response.read().decode(‘gb2312‘) print(html) print("over!")
[完整代碼]
1 import urllib 2 import urllib.parse 3 import urllib.request 4 import http.cookiejar 5 6 7 def login(): 8 9 headers = { ‘Accept‘: ‘text/html, application/xhtml+xml, image/jxr, */*‘, 10 ‘Referer‘: ‘http://jxpt.cuit.edu.cn/eol/homepage/common/index.jsp‘, 11 ‘Accept-Language‘: ‘zh-CN‘, 12 ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko‘, 13 ‘Content-Type‘: ‘application/x-www-form-urlencoded‘, 14 ‘Accept-Encoding‘: ‘gzip, deflate‘, 15 ‘Content-Length‘: 57, 16 ‘Host‘: ‘jxpt.cuit.edu.cn‘, 17 ‘Connection‘: ‘Keep-Alive‘, 18 ‘Pragma‘: ‘no-cache‘, 19 } 20 21 postData = {‘IPT_LOGINUSERNAME‘: ‘賬號‘, 22 ‘IPT_LOGINPASSWORD‘: ‘密碼‘, 23 } 24 25 #輸入賬號密碼的地址 26 loginURL = ‘http://jxpt.cuit.edu.cn/eol/homepage/common/index.jsp‘ 27 #自動記住cookie 28 cj = http.cookiejar.CookieJar() 29 opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) 30 urllib.request.install_opener(opener)# 安裝opener到全局 31 resp = urllib.request.urlopen(loginURL) 32 33 34 #post數據地址 35 postURL = ‘http://jxpt.cuit.edu.cn/eol/homepage/common/login.jsp‘ 36 #數據編碼 37 postData = urllib.parse.urlencode(postData).encode(‘utf-8‘) 38 #構造請求 39 request = urllib.request.Request(postURL, postData, headers) 40 #發送請求 41 response = urllib.request.urlopen(request) 42 43 44 respInfo = response.info() 45 #接收返回的信息 46 html = response.read().decode(‘gb2312‘) 47 print(html) 48 print("over!") 49 50 if __name__ == ‘__main__‘: 51 login()
【Python3網頁post登陸】