python selenium 登入封裝與呼叫

2022-06-23 16:27:11 字數 1526 閱讀 1297

一、登入封裝

把登入寫成一個類,裡面寫登入的方法,儲存檔案為loginclass.py

class login_go():

u'''登入類封裝'''

def __init__(self,driver):

u'''初始化driver引數'''

self.driver = driver

def login(self,username,password):

u'''輸入使用者名稱和密碼,點選登入'''

self.driver.find_element_by_id("liger-textbox-user").clear()

self.driver.find_element_by_id("liger-textbox-user").send_keys(username)

self.driver.find_element_by_id("liger-textbox-pwd_old").clear()

self.driver.find_element_by_id("liger-textbox-pwd").clear()

self.driver.find_element_by_id("liger-textbox-pwd").send_keys(password)

self.driver.find_element_by_id("go").click()

二、呼叫

from selenium import webdriver

import unittest

from loginclass import login_go

from time import sleep

class login(unittest.testcase):

def setup(self):

self.driver = webdriver.chrome()

self.driver.implicitly_wait(10)

self.driver.maximize_window()

self.driver.get(login_url)

def teardown(self):

self.driver.quit()

def case_login(self):

login_go(self.driver).login("chen","chen")#呼叫login方法

sleep(3)

result1 = self.driver.find_element_by_xpath(".//*[@id='l-topmenu-r-bottm']/span[2]").text

print(result1)

result2 = "歡迎您"

self.assertin(result2,result1,msg="失敗原因:%s中沒有發現%s"%(result1,result2))

sleep(2)

if __name__ == "__main__":

login_url = ""

unittest.main()