Switch window on Selenium

早过忘川 提交于 2019-12-06 06:59:29

问题


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.



来源:https://stackoverflow.com/questions/29124755/switch-window-on-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!