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()
posted @ 2018-09-14 13:36  巍然~chelsea  阅读(1199)  评论(0编辑  收藏  举报