package com.allin.pc;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* JS点击页面元素,主要针对于click不能点击的情况
* 以sogou为例
* @author Administrator
*/
public class javaScriptExecutor {
WebDriver driver;
String baseUrl;
JavascriptExecutor js;
@BeforeClass
public void setUp(){
baseUrl = "http://sogou.com";
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(baseUrl);
}
@AfterClass
public void tearDown(){
driver.quit();
}
@Test
public void testhandlFrom() throws Exception{
//搜索输入框
WebElement searchInput = driver.findElement(By.xpath(".//*[@id='query']"));
//查找搜狗首页搜索按钮
WebElement searchBtn = driver.findElement(By.xpath(".//*[@id='stb']"));
//在sogou首页的输入框中,输入关键字JavaScript语句进行也没见元素的单击
searchInput.sendKeys("使用JavaScript语句进行页面元素的单击");
//调用封装好的JavaScriptClick方法来实现单击sogou首页的搜索按钮
JavaScriptClick(searchBtn);
}
public void JavaScriptClick(WebElement element) throws Exception{
try{
/*
* if条件判断函数参数传入的element元素是否处于可单击状态,以及是否显示在页面上
*/
if(element.isEnabled() && element.isDisplayed()){
System.out.println("使用JavaScript进行页面单击");
//执行JavaScript语句arguments[0].click();
((JavascriptExecutor) driver).executeScript("arguments[0].click()",
element);
}else{
System.out.println("页面上的元素无法进行单击操作");
}
//当出现异常的时候,catch语句会被执行,打印相关的异常信息和出错的堆栈信息
} catch (StaleElementReferenceException e){
System.out.println("页面元素没有附加在网页中" + e.getStackTrace());
} catch (NoSuchElementException e){
System.out.println("页面元素没有找到要操作的页面元素" + e.getStackTrace());
} catch (Exception e){
System.out.println("无法完成单击操作" + e.getStackTrace());
}
}
}