使用Selenium WebDriver切换回父选项卡 [英] Switch back to parent tab using selenium webdriver

查看:167
本文介绍了使用Selenium WebDriver切换回父选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了示例代码,但是没有用.还观察到只有1个窗口句柄的2个选项卡.如何再次切换到父标签?

I wrote sample code but it is not working. Also observed that there is only 1 window handle for 2 tabs. How to switch to parent tab again?

 driver = webdriver.Firefox()
 driver.set_page_load_timeout(60)
 driver.implicitly_wait(15)
 driver.get("https://www.google.co.in")
 oldtab = driver.current_window_handle
 print oldtab
 print driver.title
 body = driver.find_element_by_tag_name("body")
 print 'new tab opened'
 driver.get("http://gmail.com/")
 print driver.title
 print 'back to old tab'
 driver.switch_to_window(oldtab)
 print driver.title
 for handle in driver.window_handles:
    print "Handle = ",handle

推荐答案

在将handle切换到父选项卡之前,您需要使用Keys切换选项卡.

You need to switch tab using Keys before switching handle to parent tab.

 from selenium.webdriver.common.keys import Keys

 driver = webdriver.Firefox()
 driver.set_page_load_timeout(60)
 driver.implicitly_wait(15)

 # First Tab
 driver.get("https://www.google.co.in")
 oldtab = driver.current_window_handle
 print driver.title
 time.sleep(3)

 # Second Tab
 driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + "t")
 driver.get("http://gmail.com/")
 newtab = driver.current_window_handle
 print driver.title
 time.sleep(3)

 # Go back to First Tab
 driver.find_element_by_tag_name("body").send_keys(Keys.ALT + Keys.NUMPAD1)
 driver.switch_to_window(oldtab)
 print driver.title
 time.sleep(3)

 # Go to Second Tab again
 driver.find_element_by_tag_name("body").send_keys(Keys.ALT + Keys.NUMPAD2)
 driver.switch_to_window(newtab)
 print driver.title
 time.sleep(3)

这篇关于使用Selenium WebDriver切换回父选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆