简体   繁体   中英

Switch window on Selenium

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM