Selenium+unittest-獲取當前窗口句柄與切換回原窗口句柄(UI自動化)


# coding=utf-8
'''
Created on 2018-9-13

@author: wiki
'''
##登錄測試:Selenium 表單填充及提交

import os,random,time,unittest
from selenium import webdriver

#創建測試用例集
class TB(unittest.TestCase):
#初始化方法:設置瀏覽器驅動
def setUp(self):
chromeDriverPath = "D:\Python35\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromeDriverPath
self.driver = webdriver.Chrome(chromeDriverPath)
self.driver.maximize_window() #最大化窗口
self.driver.implicitly_wait(10) #隱式等待
self.loginUrl = "https://staging.hairongyi.com/member/login"
self.bidUrl="https://staging.hairongyi.com/bid/537769"
self.account="18300005500"
self.password="ww123456"
self.superVerifyCode="Ed%8r5"
self.cunpwd="w123456"

def tearDown(self):
driver=self.driver
driver.quit()


def test_login(self):
'''
account:賬號
passwd:密碼
'''
driver = self.driver
#chrome瀏覽器打開登錄頁
driver.get(self.loginUrl)
time.sleep(2)
#獲取賬號輸入框
elemAccount = driver.find_element_by_id("loginName")
elemAccount.clear()
#填充賬號信息
elemAccount.send_keys(self.account)

#獲取密碼輸入框
elemPasswd = driver.find_element_by_id("unsafePassword")
elemPasswd.clear()
#填充密碼信息
elemPasswd.send_keys(self.password)

#獲取驗證碼
verifyCode=driver.find_element_by_id("verifyCode")
verifyCode.clear()
#填充驗證碼
verifyCode.send_keys(self.superVerifyCode)


#獲取提交按鈕
elemSubmit = driver.find_element_by_xpath("//*[@id=\"myform\"]/div[5]/a")
#模擬提交
elemSubmit.click()
time.sleep(5)

i=0
while i<50:
self.test_bid()
# #登錄成功判斷:判斷登錄后網頁源碼中是否含有字符串“退出”
# if "退出" in driver.page_source:
# print("登錄成功!")
# return True
# else:
# print("登錄失敗!")
# return False


def test_bid(self):
driver=self.driver
driver.get(self.bidUrl)
now_handle=driver.current_window_handle #獲取當前窗口句柄
print(now_handle) #輸出當前獲取的窗口句柄
tzinput=driver.find_element_by_xpath("/html/body/div/div[2]/div/div[2]/div[2]/div/div[2]/div/div[1]/input")
tzinput.clear()
tzinput.send_keys(random.randint(1,99))
chujiebutton=driver.find_element_by_link_text("立即出借")
chujiebutton.click()
time.sleep(1)

zhifubutton=driver.find_element_by_link_text("確認支付")
zhifubutton.click()
time.sleep(2)

#跳轉新頁面
all_handles=driver.window_handles #獲取所有窗口句柄
for handle in all_handles:
if handle !=now_handle:
print(handle) #輸出待選擇的窗口句柄
driver.switch_to_window(handle)
jiaoyipwdinput=driver.find_element_by_name("password")
jiaoyipwdinput.send_keys(self.cunpwd)

cunguanbutton=driver.find_element_by_id("nextButton")
cunguanbutton.click()
time.sleep(5)
driver.close() #關閉當前窗口
time.sleep(3)
print(now_handle) #輸出主窗口句柄
driver.switch_to_window(now_handle) #返回主窗口
time.sleep(2)




if __name__ == '__main__':
unittest.main()


免責聲明!

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



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