selenium定位方法之id
Firebug是一款前端开发工具 ,Firefox浏览器插件 (最新版本不支持使用此插件,如果要使用,必须降低浏览器版本 )
使用火狐浏览器打开http:www.baidu.com; F12键;点击左下角标注处 ;选择想要获取页面上的某一元素 如输入文本框;
由插件Firebug获得输入文本框元素为:input标签输入框的id为“kw”,
即通过id定位:
driver.findElement(By.id(" kw "));
由于单纯定位文本框并不做任何操作 所以在此调用js 元素高亮显示 代码如下图:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ByID {
public static void main(String [] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","D:\\driver\\chromedriver.exe"); //指定驱动路径
WebDriver driver = new ChromeDriver ();
driver.get("http://wwww.baidu.com");
//By id 定位
WebElement wid = driver.findElement(By.id( "kw" ));
//定位到文本,将文本高亮显示
//创建一个JavascriptExecutor对象
JavascriptExecutor js =(JavascriptExecutor)driver;
//新闻文本高亮显示颜色
js.executeScript ( "arguments[0].setAttribute('style', arguments[1]);",wid,"background: orange; border: 2px solid red;");
Thread.sleep ( 2000 );
driver.quit();
}
}
运行结果显示如下: