2014-02-19 55 views
1

我寫了示例代碼,但它不工作。還觀察到,2個選項卡只有1個窗口句柄。如何再次切換到父母標籤?使用硒webdriver切換回父母標籤

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 

回答

0

以下解決方案正在爲我工​​作。

ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform() 
time.sleep(5)  
ActionChains(driver).key_down(Keys.CONTROL).send_keys(Keys.NUMPAD1).key_up(Keys.CONTROL).perform() 
1

的另一種方式,你可以做到這一點是 - 瀏覽器打開兩個實例的說driver1driver2並在瀏覽器實例中打開相應的網址,並對其執行操作 -

driver1 = webdriver.Firefox() 
driver1.get("https://www.google.co.in") 
//perform actions for page https://www.google.co.in 


driver2 = webdriver.Firefox() 
driver2.get("http://gmail.com/") 
//perform actions for page http://gmail.com/ 
5

你需要切換標籤在將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) 
+0

This print'Google Gmail Gmail Gmail''但它應該是'Google Gmail Google Gmail'! – SIslam

0

另一個完整版本(無段)在Windows(火狐)

編輯DHIRAJ的代碼,使其在FF41工作在Windows

from selenium.webdriver.common.keys import Keys 
from selenium import webdriver 
import time 

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.CONTROL + Keys.PAGE_UP) 
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.CONTROL + Keys.PAGE_UP) 
driver.switch_to_window(newtab) 
print driver.title 
time.sleep(3) 

driver.close() 

它打印

Google 
Gmail 
Google 
Gmail