被测试的HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>《光荣之路》这个电影真的很棒! </p>
<p>主要是詹姆斯不错!</p>
</body>
</html>
方法:
String currentText = element.getText(); //获取P元素标签的文字内容
currentText.contains("光荣之路") //返回值True或者flase,与断言结合使用
currentText.startsWith("《光荣")
currentText.endsWith("很棒!")
完整代码:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CheckElement {
WebDriver driver;
String baseUrl = "E:\\Coding\\JavaCode\\WebAutomationTest\\HTML\\CheckElement.html";
@BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void isElementTextPresent() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
//使用xpth找到第一个P元素
WebElement element = driver.findElement(By.xpath("//p[1]"));
//获取P元素标签的文字内容
String currentText = element.getText();
//判断页面P标签的文字内容是否和"《光荣之路》这个电影真的很棒!"完全匹配
Assert.assertEquals("《光荣之路》这个电影真的很棒!", currentText);
Assert.assertTrue(currentText.contains("光荣之路"));
Assert.assertTrue(currentText.startsWith("《光荣"));
Assert.assertTrue(currentText.endsWith("很棒!"));
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}