Switch window on Selenium

2019-04-09 16:15发布

问题:

I am using Selenium with PhantomJS in Python. I need to open a new window and control it.

For testing purposes, I'm doing so:

from selenium import webdriver
driver = webdriver.PhantomJS()

driver.get('http://www.google.com.br')
handle = driver.execute_script('return window.open("http://www.pudim.com.br/", "any", "height = 450, width = 800, menubar=yes,scrollbars=yes,toolbar=yes,location=no,resizable=yes");')
driver.switch_to.window(driver.window_handles[1])
print(driver.current_url)

The above code works partially. The URL printed on the last message is about: blank as would be expected is http://www.pudim.com.br/

回答1:

Since there is no built-in support for selenium to work in multi-window (multi-tab) environment, fire up a new driver instead:

new_driver = webdriver.PhantomJS()
new_driver.set_window_size(800, 450)
new_driver.get("http://www.pudim.com.br/")

Also, you current code is working for me:

>>> from selenium import webdriver
>>> driver = webdriver.PhantomJS()
>>> 
>>> driver.get('http://www.google.com.br')
>>> handle = driver.execute_script('return window.open("http://www.pudim.com.br/", "any", "height = 450, width = 800, menubar=yes,scrollbars=yes,toolbar=yes,location=no,resizable=yes");')
>>> driver.switch_to.window(driver.window_handles[1])
>>> print(driver.current_url)
http://www.pudim.com.br/

Most likely, this means that you are requesting the current_url at the time the page is not loaded yet. In this case, use an Explicit Wait to wait for a specific element to appear on the page.

You can also increase the page load wait timeout, but this is not quite reliable.