使用selenium webdriver切换回父选项卡

Ven*_*enu 1 python selenium-webdriver

我写了示例代码,但它不起作用.还观察到2个标签只有1个窗口句柄.如何再次切换到父标签?

 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
Run Code Online (Sandbox Code Playgroud)

小智 5

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

 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)
Run Code Online (Sandbox Code Playgroud)