我在 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)
上面的代码部分有效。最后一条消息上打印的 URL 是about: blank
正如预期的是http://www.pudim.com.br/
既然有没有内置支持为了让 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 http://selenium-python.readthedocs.org/en/latest/waits.html#explicit-waits等待特定元素出现在页面上。
您还可以增加页面加载等待超时 http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webdriver.WebDriver.set_page_load_timeout,但这不太可靠。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)