CocoaChina 09-19
python – Selenium Switch Tabs
index_new4.html
../../../zaker_core/zaker_tpl_static/wap/tpl_keji1.html

 

由于 Firefox 不再支持 Control T, 我开始使用

????driver.execute_script ( "window.open ( ‘ URL ’ , ’ new_window ’ ) " )

我试图显示我打开的不同选项卡的标题 , 并在它们之间切换 . 对于下面的示例 , 我希望输出为 facebook,google 和返回 facebook. 现在输出是 facebook,facebook 和 facebook.

我从这里尝试了答案 , 但它也没有用:Switch back to parent tab using selenium webdriver

from selenium import webdriverdriver = webdriver.Firefox ( ) driver.get ( "http://www.facebook.com/" ) print ( driver.title ) driver.execute_script ( "window.open ( 'http://google.com', 'new_window' ) " ) print ( driver.title ) driver.switch_to.window ( driver.window_handles [ 0 ] ) print ( driver.title )

更新:

我尝试了以下代码 , 它仍然无法正常工作 .

from selenium import webdriverdriver = webdriver.Firefox ( ) driver.get ( "http://www.facebook.com/" ) print ( driver.title ) window_before = driver.window_handles [ 0 ] driver.execute_script ( "window.open ( 'http://google.com', 'new_window' ) " ) window_after = driver.window_handles [ 1 ] driver.switch_to.window ( window_after ) print ( driver.title )

最佳答案

关于 Tab / Window 切换 / 处理的几句话:

> 始终跟踪父窗口句柄 , 以便稍后根据您的用例进行遍历 .

> 在 Tabs / Windows 之间切换之前 , 始终使用WebDriverWaitexpected_conditions作为number_of_windows_to_be ( num_windows ) .

> 始终跟踪子窗口句柄 , 以便您可以在需要时进行遍历 .

> 在提取页面标题之前 , 始终将 WebDriverWait 与 expected_conditions 一起使用为title_contains ( "partial_page_title" ) .

> 这是您自己的代码 , 上面提到了一些小调整:

from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox ( executable_path=r'C:WebDriversgeckodriver.exe' ) driver.get ( "http://www.facebook.com/" ) print ( "Initial Page Title is: %s" %driver.title ) windows_before = driver.current_window_handledriver.execute_script ( "window.open ( 'http://google.com' ) " ) WebDriverWait ( driver, 10 ) .until ( EC.number_of_windows_to_be ( 2 ) ) windows_after = driver.window_handlesnew_window = [ x for x in windows_after if x != windows_before ] [ 0 ] driver.switch_to.window ( new_window ) WebDriverWait ( driver, 20 ) .until ( EC.title_contains ( "G" ) ) print ( "Page Title after first window switching is: %s" %driver.title ) driver.close ( ) driver.switch_to.window ( windows_before ) WebDriverWait ( driver, 20 ) .until ( EC.title_contains ( "F" ) ) print ( "Page Title after second window switching is: %s" %driver.title ) driver.quit ( )

> 控制台输出:

Initial Page Title is: Facebook – log in or sign upPage Title after first window switching is: GooglePage Title after second window switching is: Facebook – log in or sign up

相关标签

switch
相关文章
评论
没有更多评论了
取消

登录后才可以发布评论哦

12 我来说两句…
打开 ZAKER 参与讨论