How to switch to new window in Selenium for Python?

后端 未结 5 1882
梦谈多话
梦谈多话 2020-11-22 13:16

I am working on selenium automation project using Python.

I am facing an issue, which is handling multiple browser windows.

Scenario is as f

5条回答
  •  悲&欢浪女
    2020-11-22 13:33

    You can do it by using window_handles and switch_to_window method.

    Before clicking the link first store the window handle as

    window_before = driver.window_handles[0]
    

    after clicking the link store the window handle of newly opened window as

    window_after = driver.window_handles[1]
    

    then execute the switch to window methow to move to newly opened window

    driver.switch_to_window(window_after)
    

    and similarly you can switch between old and new window. Following is the code example

    import unittest
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    
    class GoogleOrgSearch(unittest.TestCase):
    
         def setUp(self):
             self.driver = webdriver.Firefox()
    
        def test_google_search_page(self):
             driver = self.driver
             driver.get("http://www.cdot.in")
             window_before = driver.window_handles[0]
             print window_before
             driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
             window_after = driver.window_handles[1]
             driver.switch_to_window(window_after)
             print window_after
             driver.find_element_by_link_text("ATM").click()
             driver.switch_to_window(window_before)
    
    
        def tearDown(self):
        self.driver.close()
    
    if __name__ == "__main__":
    unittest.main()
    

提交回复
热议问题