selenium2library提供的切換到新窗口的關鍵字,只有select window,而且也只能根據title、name、url去定位。如下圖所示,明顯在實際使用中是不夠的。
所以這里總結了一下其他的方法。
一、 拓展selenium2library庫。
即修改selenium的源碼。
1. *\ Python27\Lib\site-packages\Selenium2Library\locators:找到windowmanager.py文件。
打開編輯,增加方法
def select_by_handle(self, browser, toHandle):
browser.switch_to_window(toHandle)
def get_window_handles(self, browser):
return [ window_info[0] for window_info in self._get_window_infos(browser) ]
def get_current_window_handle(self, browser):
return browser.get_current_window_handle()
2. *:\Python27\Lib\site-packages\Selenium2Library\keywords:找到_browsermanagement.py文件。
打開編輯,增加方法
def select_window_by_handle(self, locator=None):
self._window_manager.select_by_handle(self._current_browser(), locator)
def get_window_handles(self):
"""Returns and logs handles of all windows known to the browser."""
return self._log_list(self._window_manager.get_window_handles(self._current_browser()))
def get_current_window_handle(self):
"""Returns and logs handle of current window known to the browser."""
return self._log_list(self._window_manager.get_current_window_handle(self._current_browser()))
二、編寫自己的關鍵字
使用robotframework:
1. 創建“Index Item From List”關鍵字
Index Item From List
[Arguments] ${element} @{items}
${index}= Set Variable ${0}
: FOR ${item} IN @{items}
\ Return From Keyword If '${element}'=='${item}' ${index}
Return From Keyword ${-1}
2. 創建“get 新窗口”關鍵字
get新窗口
[Arguments] @{win_all}
@{win_all_curr} Get Window Handles
${idx}= Set Variable ${-1}
: FOR ${win} IN @{win_all_curr}
\ ${idx} Index Item From List ${win} @{win_all}
\ Return From Keyword If ${idx} == ${-1} ${win}
\ Comment Should be True 0 == 1 #No win handle or no new handle
Should Be True ${idx} msg=No Window handles or no new handle
3. 創建“select新窗口/原窗口”關鍵字
[Arguments] ${keyword} ${item}
${win_curr}= Get Current Window Handle
@{win_hds}= Get Window Handles
Run Keyword ${keyword} ${item}
sleep 3
${win_child}= get新窗口 @{win_hds}
Select Window By Handle ${win_child}
[Return] ${win_child} # ${win_curr} |也可以返回這個,就是返回原窗口
4. 使用我們寫好的關鍵字吧。
看上面3個關鍵字,可能有些人會不是很懂,不是很理解到底怎么切換的,所以這里寫個調用的方法,方便理解。
102002-隨機打開箱包寶貝
click element css=li>a[href='#/list/?category1=熱賣箱包']
sleep 3
@{items} Get Webelements css=.item_picture>a[href]
${item}= 隨機選擇元素賦值 @{items}
select新窗口 click element ${item}
例子說明:1. 先是打開了一個箱包的新窗口;
2. 第3、4行代碼都是隨機獲得一個href的鏈接。
3. 最后一行,就是調用我們的“select新窗口”來切換到新打開的“href”的窗口。
里面的邏輯,把代碼帶入看,
select新窗口 click element ${item}帶入看
${win_curr}= Get Current Window Handle #獲得當前窗口
@{win_hds}= Get Window Handles #獲得當前所有的窗口
Run Keyword click element ${item} #帶入后,這里就是打開我們的href新窗口
sleep 3
${win_child}= get新窗口 @{win_hds} #get新窗口會獲取打開href新窗口后的所有窗口,會比@{win_hds}多這么一個href。這樣就可以循環得到它了。
Select Window By Handle ${win_child}
[Return] ${win_child}
本章大致結束,后面有新的更好的,回慢慢補充。
