简体   繁体   English

在Selenium上切换窗口

[英]Switch window on Selenium

I am using Selenium with PhantomJS in Python. 我在Python中使用Selenium和PhantomJS。 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/ 最后一条消息上打印的URL about: blankabout: blank如预期的那样是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: 由于没有内置支持 selenium在多窗口(多标签)环境中工作,因此启动新驱动程序:

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. 最有可能的是,这意味着您在页面尚未加载时请求current_url In this case, use an Explicit Wait to wait for a specific element to appear on the page. 在这种情况下,使用Explicit Wait等待特定元素出现在页面上。

You can also increase the page load wait timeout , but this is not quite reliable. 您还可以增加页面加载等待超时 ,但这不太可靠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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