How to switch to new window in Selenium for Python?

后端 未结 5 1946
梦谈多话
梦谈多话 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:50

    On top of the answers already given, to open a new tab the javascript command window.open() can be used.

    For example:

    # Opens a new tab
    self.driver.execute_script("window.open()")
    
    # Switch to the newly opened tab
    self.driver.switch_to.window(self.driver.window_handles[1])
    
    # Navigate to new URL in new tab
    self.driver.get("https://google.com")
    # Run other commands in the new tab here
    

    You're then able to close the original tab as follows

    # Switch to original tab
    self.driver.switch_to.window(self.driver.window_handles[0])
    
    # Close original tab
    self.driver.close()
    
    # Switch back to newly opened tab, which is now in position 0
    self.driver.switch_to.window(self.driver.window_handles[0])
    

    Or close the newly opened tab

    # Close current tab
    self.driver.close()
    
    # Switch back to original tab
    self.driver.switch_to.window(self.driver.window_handles[0])
    

    Hope this helps.

提交回复
热议问题