WebDriver中Action使用:以選擇多行為例
在我們使用selenium 1.0的時候,如果需要選擇多行,可以模擬鍵盤操作按下Ctrl以及放開Ctrl鍵來控制,提供的API為:
selenium.controlKeyDown();
//select action
selenium.controlKeyUp();
可是到了selenium 2上,我們會發現這些函式已經失效了。那麼,我們就必須要藉助於WebDriver提供的Action來實現等效功能。
Actions提供給了我們模擬複雜的使用者操作的API,它能夠用來替換對Keyboard及Mouse的直接使用。可以呼叫該類的多個動作方法來建立一個組合Action。
例1:模擬按鍵Ctrl+F5
Ctrl is a modifier key but F5 is not. You probably want to use:
Actions actionObject = new Actions(webDriver);
actionObject.keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();
有時候我們會發現當有很多action時候,perform()前面通常會呼叫build(),這時候可以檢視build()的作用。Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder
state, so subsequent calls to build() will contain fresh sequences). 主要目的就是建立一個組合action以準備執行,並且讓新的action系列可以加入到下一個build()中去。
例2:模擬選擇多行
Actions builder = new Actions(driverUtil.getDriver());
builder.keyDown(Keys.CONTROL).moveToElement(element1).click().moveToElement(element2).click().keyUp(Keys.CONTROL).perform();
這個例子將一系列action放在一起然後執行。
我也有嘗試成功類似於selenium 1中的邏輯的實現,即利用action來執行keydown和keyup,其他操作則按照正常的webdriver操作。
Actions builder = new Actions(webDriver); builder.keyDown(Keys.CONTROL).perform(); webDriver.findElement(row1).click(); webDriver.findElement(row2).click(); builder.keyUp(Keys.CONTROL).perform();
利用Keyboard和Mouse模擬
事實上,我麼也可以不適用Actions而直接利用Keyboard以及mouse來模擬。
WebElement someElement = driver.findElement(By.id("some"));
WebElement someOtherElement = driver.findElement(By.id("other"));
Mouse mouse = ((HasInputDevices) driver).getMouse();
Keyboard keyboard = ((HasInputDevices) driver).getKeyboard();
keyboard.pressKey(Keys.CONTROL);
mouse.click((Coordinates) someElement.getLocation());
mouse.click((Coordinates) someOtherElement.getLocation());
keyboard.releaseKey(Keys.CONTROL);
利用Javascript執行https://groups.google.com/forum/#!topic/webdriver/Aewqs_MxJrM
如果以上方法嘗試都沒有效果,則可以參考上一行連結的一個利用script的方法。
I realize this discussion is a little old but I ran across it multiple times while facing this issue. It took me a few hours but I found a way around it. I don't know why, but keyDown actions (at least with CTRL) in the FirefoxDriver don't register. The solution I finally came up with was to use javascript to simulate a mouse event with a CTRL key modifier. I'm not sure if this will work for all cases but in my case it did what I needed it to do.
((FirefoxDriver)driver).executeScript("var evt = document.createEvent('MouseEvent'); " +
"evt.initMouseEvent('mousedown', true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null); " +
"document.getElementById('" + someWebElement.getAttribute("id") + "').dispatchEvent(evt);" +
"return;");