1、 對input執(zhí)行輸入
直接設(shè)置value屬性, 此方法主要應(yīng)對輸入框自動補全以及readonly屬性的element,sendkeys不穩(wěn)定
比如:
//inputbox is a WebElement
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value="北京"", from_inpox);
對此可以封裝一個typeQuick的方法
/**
* @author Young
* @param locator
* @param values
* @throws Exception
*/
protected void typeQuick(Locator locator, String values) throws Exception {
WebElement e = findElement(driver, locator);
log.info("type value is: " + values);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value=""+values+""", e);
去掉只讀屬性
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].removeAttribute("+"readonly"+")", e);
2.對富文本框的操作
主要應(yīng)對富文本框,可以封裝獲取富文本框內(nèi)容和設(shè)置富文本路況內(nèi)容的方法
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement editor = driver.findElement(By.tagName("body"));
js.executeScript(
"arguments[0].innerHTML = '<h1>Selenium Test </h1>I love Selenium <br> this article Post By Selenium WebDriver<br><h2>Create By Young</h2>'",
editor);
設(shè)置富文本框內(nèi)容
/**
* @author Young
* @param locator
* @param text
*/
protected void setRichTextBox(Locator locator, String text) {
WebElement e = findElement(driver, locator);
log.info("type value is: " + text);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].innerHTML = "" + text + """, e);
}
獲取富文本框內(nèi)容:
/**
* @author Young
* @param locator
* @param text
* @return
*/
protected String getRichTextBox(Locator locator, String text) {
WebElement e = findElement(driver, locator);
log.info("type value is: " + text);
JavascriptExecutor js = (JavascriptExecutor) driver;
String result=(String) js.executeScript("arguments[0].getInnerHTML()", e);
return result;
}
3. 滾動到指定位置
為啥使用滾動? 因為如果頁面沒有完全顯示,element如果是在下拉之后才能顯示出來,只能先滾動到該元素才能進行click,否則是不能click操作
JavascriptExecutor js=(JavascriptExecutor)driver;
// roll down and keep the element to the center of browser
js.executeScript("arguments[0].scrollIntoViewIfNeeded(true);", download);
可以封裝滾動到元素的方法的
/**
* @author Young
* @param locator
*/
protected void scrollToElement(Locator locator) {
WebElement e = findElement(driver, locator);
log.info("scroll view element");
JavascriptExecutor js = (JavascriptExecutor) driver;
// roll down and keep the element to the center of browser
js.executeScript("arguments[0].scrollIntoViewIfNeeded(true);", e);
}
Dom event 事件的封裝
/**
* For DOM Event
* @author Young
* @param locator
* @param event
* please refer to: http://www.w3school.com.cn/jsref/dom_obj_event.asp
*
*/
public void DOMEvent(Locator locator,String event)
{
JavascriptExecutor jse=((JavascriptExecutor)driver);
String js="var event;if (document.createEvent){event = document.createEvent("HTMLEvents");event.initEvent(""+event+"", true, false);arguments[0].dispatchEvent(event);} else {arguments[0].fireEvent("on"+event+"")}";
jse.executeScript(js, findElement(driver,locator)) ;
}
出處:http://www.cnblogs.com/tobecrazy/