Python 模擬登陸的兩種實(shí)現(xiàn)方法
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ū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
淺談keras通過model.fit_generator訓(xùn)練模型(節(jié)省內(nèi)存)
這篇文章主要介紹了淺談keras通過model.fit_generator訓(xùn)練模型(節(jié)省內(nèi)存),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python實(shí)現(xiàn)人工蜂群算法的示例代碼
ABC,即人工蜂群算法(Artificial?Bee?Colony?Algorithm),由Karaboga等人提出,這篇文章主要介紹了人工蜂群算法的概念與Python實(shí)現(xiàn),感興趣的可以了解一下2023-08-08
基于tkinter中ttk控件的width-height設(shè)置方式
這篇文章主要介紹了基于tkinter中ttk控件的width-height設(shè)置方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
Python中PyExecJS(執(zhí)行JS代碼庫)的具體使用
pyexecjs是一個(gè)用Python來執(zhí)行JavaScript代碼的工具庫,本文主要介紹了Python中PyExecJS(執(zhí)行JS代碼庫)的具體使用,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02

