首页 > 代码库 > selenium执行js

selenium执行js

import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.FirefoxDriver;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass;import org.testng.annotations.Test;public class TestBaidu {    public static WebDriver driver;    /*     * @BeforeClass 
   * public void setUp() { driver = new FirefoxDriver(); * driver.manage().window().maximize(); } * * @AfterClass
   * public void tearDown() { driver.close(); driver.quit(); } * * @Test
   * public void process() { * driver.navigate().to("
http://www.baidu.com"); // * driver.findElement(By.id("kw")); JavascriptExecutor j = * (JavascriptExecutor) driver; * j.executeScript("document.getElementById(\"kw\").value=http://www.mamicode.com/"测试\""); } */ public static void main(String[] args) throws InterruptedException { // 可能需要设置firefox的路径 driver = new FirefoxDriver(); try { driver.manage().window().maximize(); driver.get("http://www.baidu.com"); // 利用webdriver键入搜索关键字 // driver.findElement(By.id("kw")).sendKeys("yeetrack"); // 利用js代码键入搜索关键字 ((JavascriptExecutor) driver) .executeScript("document.getElementById(\"kw\").value=http://www.mamicode.com/"测试\""); // 利用js代码取出关键字 String keyword = (String) ((JavascriptExecutor) driver) .executeScript("var input = document.getElementById(\"kw\").value;return input"); System.out.println(keyword); driver.findElement(By.id("su")).click(); TimeUnit.SECONDS.sleep(5); } catch (Exception e) { e.printStackTrace(); } finally { driver.quit(); } }}

selenium执行js