Skip to main content
 首页 » 编程设计

python之使用 selenium webdriver 切换回父选项卡

2025年05月04日46jackei

我编写了示例代码,但它不起作用。还观察到 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 

请您参考如下方法:

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

 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)