python-自動登錄禪道


from bs4 import BeautifulSoup
import hashlib
import requests
import re
from tool.request_data_change_to_StrEncode import request_data_change_to_str
import os
import json

class zentao_login(object):
    global file_login_info
    file_login_info = './login_info.txt'#登錄網頁存放至本地,用於提取verifyRand

    def __init__(self):
        self.data_to_str=request_data_change_to_str()
        self.session = requests.session()
        self.host = 'http://xxxx'
        self.header={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"}

    def md5_key(self,str):#md5加密
        m = hashlib.md5()
        b = str.encode(encoding='utf-8')
        m.update(b)
        return m.hexdigest()

    def login(self,user='admin',pw='sss',file=file_login_info):#登錄
        url=self.host+'/zentao/user-login.html'
        content = self.session.get(url,headers = self.header)
        with open(file,'w',encoding='utf-8') as file:#將網頁保存到本地
            file.write(content.text)
        verifyRandstr=self.read_verifyRandstr()#獲取登錄字符串
        password=self.md5_key(self.md5_key(pw)+verifyRandstr)#md5加密密碼
        login_url=self.host+'/zentao/user-login.html'
        data=self.data_to_str.requestDataToStr_firefoxAndChrome('''account: admin
    password: %s
    passwordStrength: 1
    referer: /zentao/
    verifyRand: %s
    keepLogin: 1'''%(password,verifyRandstr))
        request_login=self.session.post(url=login_url,data=data,headers=self.header,allow_redirects=True)#登錄
        if "self.location='/zentao/" in request_login.text:
            #判斷登錄是否成功,成功后將cookie寫入文件
            cookies = requests.utils.dict_from_cookiejar(request_login.cookies) #拿到所有的cookie
            temp_str = ''#定義cookie字符串
            # 獲取sessionid,如果不保存至header,用requests直接請求會出錯
            session_str = 'zentaosid=' + request_login.cookies.values()[-1]
            for key,value in cookies.items():
                if (key=='zp' or key=='za' or key=='keepLogin'):
                    str='{}={};'.format(key,value)#拼接cookie,key/value
                    temp_str+=str#將拼接完成的cookie,添加至最終的cookie字符串
            self.header['Cookie']=temp_str+session_str#將處理完成的cookie添加至請求header
            with open('./zentao_header.txt','w',encoding='utf-8') as zentao_header:#將header寫入至文件
                zentao_header.write(repr(self.header))
        elif "alert('登錄失敗,請檢查您的用戶名或密碼是否填寫正確。')" in request_login.text:
            # 判斷由於密碼錯誤引起的登陸失敗
            raise Exception('密碼錯誤,登錄失敗,請重試')
        else:
            # 判斷由於其他情況引起的登錄失敗
            raise Exception(request_login.text)

    def read_verifyRandstr(self,file=file_login_info):#匹配verifyRand
        with open(file,'r',encoding='utf-8') as file_read:
            login_html_info=file_read.read()
            soup=BeautifulSoup(login_html_info,'lxml')
            button=soup.find_all('input',attrs={'type': re.compile("hidden"),'id': re.compile("verifyRand")})[0]['value']
        return button

    def load_header(self,user='admin',pw='test2019zentao',file='./zentao_header.txt'):
        #測試cookie是否有效,有效的話就直接使用,無效就觸發重新登錄
        '''這里遇到了一個問題,如果header里沒有保存sessionid,那么用requests直接請求會出錯,這時候需要用session請求才行,
            如果header里保存了sessionid,那么用requests請求即可,當然用session請求也不會有問題,
            所以最終還是把session保存進了header,與token認證還真不一樣'''
        try:#處理zentao_header.txt不存在的情況
            with open(file,'r',encoding='utf-8') as header_info:
                header=eval(header_info.read())
            url_bug = self.host + '/zentao/bug-browse.json'
            re_bug = requests.get(url=url_bug, headers=header)
            if "self.location='/zentao/user-login-" in re_bug.text:
                self.login(user, pw)
            return header
        except FileNotFoundError as error:
            print(error,'執行登錄')
            self.login()
            self.load_header()



if __name__=="__main__":
    zt=zentao_login()
    # zt.login()
    zt.load_header()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM