在硒上切换窗口 [英] Switch window on Selenium

查看:85
本文介绍了在硒上切换窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中将Selenium与PhantomJS一起使用. 我需要打开一个新窗口并对其进行控制.

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)

上面的代码部分起作用.在最后一条消息上打印的URL是about: blank,如预期的那样是http://www.pudim.com.br/

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/

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

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.

这篇关于在硒上切换窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆