簡體   English   中英

在Selenium上切換窗口

[英]Switch window on Selenium

我在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: blankabout: 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等待特定元素出現在頁面上。

您還可以增加頁面加載等待超時 ,但這不太可靠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM