WebDriver应用实例(java)——使用JavaScriptExecutor单击元素

        使用JavaScriptExecutor对象来实现页面元素的单击动作。这种方法主要用于解决在某些情况下,页面元素的.click()方法无法生效。

被测试页面:http://www.baidu.com

实例代码如下:

package cn.om.webdriverapi;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;

public class TestClickButtonWithJS {
	// 使用JavaScriptExecutor对象来实现页面单击动作。主要用于某些情况下,页面元素的click()方法无法生效

	WebDriver driver;
	String baseURL;
	JavascriptExecutor jsexecutor;

	@BeforeMethod
	public void beforeMethod() {
		baseURL = "http://www.baidu.com";
		System.setProperty("webdriver.firefox.bin", "E:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		driver.get(baseURL);
	}

	@AfterMethod
	public void afterMethod() {
		driver.quit();
	}

	@Test
	public void testClickButtonWithJavaScript() {
		//查找搜索按钮
		WebElement but = driver.findElement(By.id("su"));
		WebElement input = driver.findElement(By.id("kw"));

		input.sendKeys("使用JavaScript语句来进行页面元素的单击");
		JavaScriptClick(but);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void JavaScriptClick(WebElement element) {
		jsexecutor = (JavascriptExecutor) driver;
		try {
			// 判断传入的element元素是否处于可单击状态,以及是否能显示在页面上
			if (element.isEnabled() && element.isDisplayed()) {
				System.out.println("使用JavaScript进行页面元素的单击");
				// 执行JavaScript语句arguments[0].click();
				//argumets[0]表示第一个参数,即element
				jsexecutor.executeScript("arguments[0].click();", element);
			} else {
				System.out.println("页面上的元素无法进行单击操作");
			}
		} catch (StaleElementReferenceException e) {
			// TODO: handle exception
			System.out.println("页面元素没有附加在网页中"+e.getStackTrace());
		} catch (NoSuchElementException e) {
			// TODO: handle exception
			System.out.println("在页面中没有找到要操作的元素"+e.getStackTrace());
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("无法完成单击动作"+e.getStackTrace());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/vikeyyyy/article/details/80182917