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());
}
}
}