Python 模擬登陸的兩種實(shí)現(xiàn)方法
有時(shí)候我們的抓取項(xiàng)目時(shí)需要登陸到某個(gè)網(wǎng)站上,才能看見某些內(nèi)容的,所以模擬登陸功能就必不可少了,散仙這次寫的文章,主要有2個(gè)例子,一個(gè)是普通寫法寫的,另外一個(gè)是基于面向?qū)ο髮懙摹?/p>
模擬登陸的重點(diǎn),在于找到表單真實(shí)的提交地址,然后攜帶cookie,post數(shù)據(jù)即可,只要登陸成功,我們就可以訪問其他任意網(wǎng)頁,從而獲取網(wǎng)頁內(nèi)容。
方式一:
import urllib.request import urllib.parse import http.cookiejar #post的內(nèi)容 values={ 'logon.x':'linke', 'password':'xxxx', 'username':'xxxxx' } #登陸的地址 logUrl="http://192.168.32.112:8080/templates/index/hrlogon.do" #構(gòu)建cook cook=http.cookiejar.CookieJar() #構(gòu)建openner openner=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cook)) #添加headers openner.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')] r=openner.open(logUrl,urllib.parse.urlencode(values).encode()) #print(r.read().decode('gbk')) r=openner.open("http://192.168.132.62:8080/kq/kqself/card/carddata.do?b_query=link") print(r.read().decode('gbk')) 方式二:
import urllib import urllib.request import urllib.parse import http.cookiejar import re class loginRLKQ: post_data=b""; def __init__(self): #初始化類,cook的值 cj=http.cookiejar.CookieJar() opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) opener.addheaders=[('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')] #初始化全局opener urllib.request.install_opener(opener) #login方法需要加入post數(shù)據(jù) def login(self,loginurl,encode): #模擬登陸 req=urllib.request.Request(loginurl,self.post_data) rep=urllib.request.urlopen(req) d=rep.read() #print(d) d=d.decode(encode) return d #登陸之后獲取其他網(wǎng)頁方法 def getUrlContent(self,url,encode): req2=urllib.request.Request(url) rep2=urllib.request.urlopen(req2) d2=rep2.read() d22=d2.decode(encode) return d22 if __name__=="__main__": #實(shí)例化類 x=loginRLKQ() #給post數(shù)據(jù)賦值 x.post_data=urllib.parse.urlencode({'username':"xxdd",'password':'xxdd','logon.x':'linke'}).encode(encoding="gbk") #登陸 y=x.login("http://192.168.132.61:8080/templates/index/hrlogon.do","gbk") #獲取網(wǎng)頁信息 print(x.getUrlContent("http://192.124.32.16:8080/kq/kqself/card/carddata.do?b_query=link","gbk")) 以上就是Python 模擬登陸的實(shí)現(xiàn)方法,如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選