在Selenium上切换窗口

时间:2015-03-18 14:28:57

标签: python selenium selenium-webdriver phantomjs

我在Python中使用Selenium和PhantomJS。 我需要打开一个新窗口并控制它。

出于测试目的,我这样做:

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)

以上代码部分有效。最后一条消息上打印的网址为about: blank,预期为http://www.pudim.com.br/

1 个答案:

答案 0 :(得分:5)

由于没有内置支持,因此selenium可以在多窗口(多标签)环境中工作,而是启动新的驱动程序:

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

此外,您当前的代码对我有用:

>>> 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/

最有可能的是,这意味着您在页面尚未加载时请求current_url。在这种情况下,使用Explicit Wait等待特定元素出现在页面上。

你也可以增加page load wait timeout,但这不太可靠。