selenium自动化
1、废话不多说,上代码(有注释)
public static void main(String args[]) {
//加载谷歌的驱动 其他驱动同样道理 先引入驱动,再构建环境
File file = new File("C:\\Users\\acer\\Desktop\\chromedriver_win32\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
webDriver = new ChromeDriver();
try {
//打开指定页面 使用谷歌打开一个新的页面
webDriver.get("https://www.baidu.com/");
//睡眠3秒 防止加载失败
Thread.sleep(3000);
// String windowHandle = webDriver.getWindowHandle();//获取当前句柄
//为搜索框赋值
webDriver.findElement(By.id("kw")).sendKeys("远方的姑娘你可知道");
//点击搜索
webDriver.findElement(By.id("su")).click();
//睡眠1秒
Thread.sleep(1000);
//使用xpath选择器 选取所包含的所有标签内容
List<WebElement> a = webDriver.findElements(By.xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div"));
int size = a.size();
//循环所获取的内容
for (int i=0;i<size;i++){
WebElement webElement = a.get(i);
//根据className()定位,获取内容
String a1 = webElement.findElement(By.className("t")).getText();
System.out.println(a1);
//睡眠1秒
Thread.sleep(1000);
//使用linkText()定位,然后点击打开链接
webElement.findElement(By.linkText(a1)).click();
}
} catch (Exception e) {
// webDriver.quit();//退出 既关闭所打开的浏览器
System.out.println(e.getMessage());
}
}
2、效果图
所打开的页面:
控制台输出:
3、其他常用的方法与选择器
webElement.click();//点击
webElement.getAttribute("");//获取属性值
webElement.getText();//获取所在标签中的所有内容
webElement.getTagName();//获取标签名字
webElement.findElement(By.xpath(""));//xpath选择器
webElement.findElement(By.id(""));//id选择器
webElement.findElement(By.name(""));//name选择器
webElement.findElement(By.tagName(""));//标签选择器
webElement.findElement(By.cssSelector(""));//css选择器
webElement.findElement(By.className(""));//class选择器
webElement.findElement(By.linkText(""));//内容选择器
webElement.findElement(By.partialLinkText(""));//也是内容选择器