本篇继续讲webdriver查找元素方法,这篇介绍By LinkText方法。什么是linktext呢,就是我们在网页上看到有一个链接,上面有一个文字描述,点击这个文字,就可以跳转到其他页面。我们这里以百度首页举例,点击首页右上角那个新闻链接,观察是否进入到百度新闻页面。
相关脚本代码如下:
- package lessons;
- import org.openqa.selenium.By;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.chrome.ChromeDriver;
- public class FindElement_LinkText {
- public static void main(String[] args) throws Exception {
- System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");
- WebDriver driver = new ChromeDriver();
- driver.manage().window().maximize();
- driver.get("https://www.baidu.com");
- //By linkText 查找元素
- driver.findElement(By.linkText("新闻")).click();
- Thread.sleep(1000);
- //判断打开页面是不是百度新闻,这里用url作为验证
- assert driver.getCurrentUrl() == "http://news.baidu.com";
- }
- }
package lessons;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FindElement_LinkText {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.baidu.com");
//By linkText 查找元素
driver.findElement(By.linkText("新闻")).click();
Thread.sleep(1000);
//判断打开页面是不是百度新闻,这里用url作为验证
assert driver.getCurrentUrl() == "http://news.baidu.com";
}
}
上面添加了一个assert判断,通过判断新打开的url是不是我们希望的url去断言,我们链接跳转是正确的。以后,看到测试页面也有类似百度首页,点击“新闻”进入下一个页面的情况,你就要想起来有By LinkText 这个方法可以用来定位该类型元素。