一、Selenium Webdriver 常用的API
(一)引入依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
开始:
public static void main(String[] args) throws InterruptedException {
ChromeOptions options = new ChromeOptions();
//允许任何来源的远程连接,这样可以避免一些跨域问题。
options.addArguments("--remote-allow-origins=*");
//初始化 chrome 浏览器 driver 对象
WebDriver webDriver = new ChromeDriver(options);
// 访问指定网页
webDriver.get("https://juejin.cn");
//开始操作页面
//……
}
其它浏览器:
WebDriver driver = new FirefoxDriver(); // Firefox浏览器
WebDriver driver = new EdgeDriver(); // Edge浏览器
WebDriver driver = new InternetExplorerDriver(); // Internet Explorer浏览器
……
(二)元素的定位
要想操作一个对象,首先应该识别这个对象。通过下面的 API,可以获取页面上的标签对象,从而来操作它们。
1.css选择器定位
css选择器定位,在css中有标签选择器、类选择器、id选择器、后代选择器、子选择器、并集选择器……它们对应的语法在在这里也适用。
public static void main(String[] args) throws InterruptedException {
ChromeOptions options = new ChromeOptions();
//允许任何来源的远程连接,这样可以避免一些跨域问题。
options.addArguments("--remote-allow-origins=*");
WebDriver webDriver = new ChromeDriver(options);
// 访问指定网页
webDriver.get("https://juejin.cn");
//css 选择器 方式1:id选择
WebElement element = webDriver.findElement(By.cssSelector("#elementId"));
//css 选择器 方式2:类选择
WebElement element2 = webDriver.findElement(By.cssSelector(".elementClass"));
//css 选择器 方式3:后代选择
WebElement element2 = webDriver.findElement(By.cssSelector(".elementClass1 .elementClass2……"));
//其它方式
……
}
案例:我想要用webDriver在掘金主页搜索框中输入“selenium”并点击搜索。
- 先看掘金主页源码中搜索框、搜索按钮的标签属性。
- 代码
public static void main(String[] args) {
ChromeOptions options = new ChromeOptions();
//允许任何来源的远程连接,这样可以避免一些跨域问题。
options.addArguments("--remote-allow-origins=*");
WebDriver webDriver = new ChromeDriver(options);
// 访问指定网页
webDriver.get("https://juejin.cn");
//获取搜索框
WebElement input = webDriver.findElement(By.cssSelector(".search-input"));
//输入值
input.sendKeys("java");
//获取搜索按钮
WebElement seach = webDriver.findElement(By.cssSelector(".seach-icon-container"));
//点击该元素
seach.click();
}
为了简洁,文章后面就不放查找标签class属性的截图了,知道怎么查找就行了。
2.id 定位
这个跟 css选择器定位 类似,可以作为它的简便写法
webDriver.findElement(By.id("页面元素的id值"));
3.name 定位
如果这个元素有name属性,并且元素的name命名在整个页面是唯一的,那么我们可以用name来定位这个 元素。
webDriver.findElement(By.name("页面元素的name值"));
4.className、tagName 定位
className就是根据类名字选择,tagName是根据标签名选择。
webDriver.findElement(By.className("class的名字"));
webDriver.findElement(By.tagName("标签的名字"));
5.linkText定位
对一个文字链接进行定位,我们可以通过链接内容,也就是 link text 来定位。
//获取链接元素
WebElement link = webDriver.findElement(By.linkText("链接文本"));
自动进入首页的“后端”页面
public static void main(String[] args) {
ChromeOptions options = new ChromeOptions();
//允许任何来源的远程连接,这样可以避免一些跨域问题。
options.addArguments("--remote-allow-origins=*");
WebDriver webDriver = new ChromeDriver(options);
// 访问指定网页
webDriver.get("https://juejin.cn");
//获取链接元素
WebElement link = webDriver.findElement(By.linkText("后端"));
//点击元素
link.click();
}
6.partialLinkText定位
只用链接的一部分文字进行匹配。
//获取带“text”的链接
WebElement link = webDriver.findElement(By.partialLinkText("text"