1.安裝模塊
2.准備aspx登錄頁面
3.示例代碼
1 #coding:utf-8 2 import re 3 from bs4 import BeautifulSoup 4 import gzip 5 import urllib.request 6 import urllib.parse 7 import http.cookiejar 8 import ssl 9 import time 10 11 loginurl='http://192.168.0.108:8005/login.aspx' 12 vercodeurl='http://192.168.0.108:8005/vercode.aspx?r=%d' 13 14 heads={ 15 "Accept":"text/html, application/xhtml+xml, */*", 16 "Accept-Language":"zh-CN", 17 "User-Agent":"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0", 18 "Accept-Encoding": "gzip, deflate", 19 "Host": "http://192.168.0.108:8005", 20 "DNT": "1", 21 "Connection": "Keep-Alive" 22 } 23 24 def get_opener(heads): 25 cj=http.cookiejar.CookieJar() 26 pro=urllib.request.HTTPCookieProcessor(cj) 27 opener=urllib.request.build_opener(pro) 28 header=[] 29 for key,value in heads.items(): 30 header.append((key,value)) 31 opener.addheaders=header 32 return opener 33 34 def ungzip(data): 35 try: 36 data=gzip.decompress(data) 37 #with open("222.txt",'wb') as file: 38 #file.write(data) 39 except: 40 pass 41 return data 42 43 if __name__=="__main__": 44 ssl._create_default_https_context = ssl._create_unverified_context 45 opener=get_opener(heads) 46 op=opener.open(loginurl) 47 data1=op.read() 48 data1=ungzip(data1).decode('utf-8') 49 soup=BeautifulSoup(data1,"html.parser") 50 51 VIEWSTATE=soup.find("input",{'type':'hidden','name':'__VIEWSTATE'}).get("value") 52 VIEWSTATEGENERATOR=soup.find("input",{'type':'hidden','name':'__VIEWSTATEGENERATOR'}).get("value") 53 EVENTVALIDATION=soup.find("input",{'type':'hidden','name':'__EVENTVALIDATION'}).get("value") 54 55 '''正則獲取隱藏值 56 regular = { 57 'viewstate': re.compile(r'id="__VIEWSTATE" value="(.+)" />'), 58 'eventvalidation': re.compile(r'id="__EVENTVALIDATION" value="(.+)" />') 59 } 60 print(regular['viewstate'].findall(data1)[0]) 61 ''' 62 63 vercodedata=opener.open(vercodeurl% (time.time() * 1000)).read() 64 with open("auto100.jpeg",'wb') as file: 65 file.write(vercodedata) 66 yzm=input("請輸入驗證碼:") 67 postdata={ 68 "__VIEWSTATE":VIEWSTATE, 69 "__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR, 70 "__EVENTVALIDATION":EVENTVALIDATION, 71 "username":"sulin", 72 "userpwd":"123", 73 "btnlogin":"登錄", 74 "vercode":yzm 75 } 76 postdata=urllib.parse.urlencode(postdata).encode('utf-8') 77 78 op2=opener.open(loginurl,postdata) 79 login_data=op2.read() 80 data=ungzip(login_data).decode("utf-8") 81 print(data) 82
4.測試結果