Selenium之JS操作

  1. 去除元素只读属性

    	 JavascriptExecutor js = (JavascriptExecutor) driver;
    	 js.executeScript("arguments[0].removeAttribute(\"+"readonly"+\")", element);
    
  2. 文本输入框赋值`

    JavascriptExecutor js = (JavascriptExecutor) driver;
    String jsText = "var sum = document.getElementById('id'); sum.value='" + text + "';"
    js.executeScript(jsText);`
    

3.设置富文本框的内容

	JavascriptExecutor js = (JavascriptExecutor) driver;
	WebElement editor = driver.findElement(By.tagName("body"));
	js.executeScript("arguments[0].innerHTML = '

Selenium Test

I love Selenium
this article Post By Selenium WebDriver

Create By Young

'",element);

4.获取富文本框内容

        JavascriptExecutor js = (JavascriptExecutor) driver;
        String result=(String) js.executeScript("var result=arguments[0].innerHTML;return result", element);

5.元素滚动至可见位置

	//true时与顶部对其  false与底部对齐
		JavascriptExecutor js = (JavascriptExecutor) driver;
        // roll down and keep the element to the center of browser
        js.executeScript("arguments[0].scrollIntoView(true);", e);

6.元素滚动至可见位置_如果当前可见,则不会发生滚动

		JavascriptExecutor js = (JavascriptExecutor) driver;
        // roll down and keep the element to the center of browser
        js.executeScript("arguments[0].scrollIntoViewIfNeeded(true);", e);

7.元素高亮展示

	JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element,"border: 2px solid red;" #边框border:2px; red红色)

8.元素点击

        JavascriptExecutor js = (JavascriptExecutor)driver;
   		js.executeScript("arguments[0].click();",element);

9.利用js代码键入搜索关键字

   JavascriptExecutor js = (JavascriptExecutor)driver;
   js.executeScript("document.getElementById(\"kw\").value=\"yeetrack\"");
  1. //利用js代码取出关键字

     JavascriptExecutor js = (JavascriptExecutor)driver;
     js.executeScript("var input = document.getElementById(\"kw\").value;return input");
    

11./用js判断页面加载完毕,返回complete

    js.executeScript("return document.readyState").toString();

你可能感兴趣的:(Selenium)