如何用Selenium Java获取结果并断言其大于5000及相关问题
Selenium Java获取搜索结果数值并断言大于5000的实现
核心解决步骤
提取并转换搜索结果数值
Google搜索结果的result-stats元素文本格式类似“约 1,200,000 条结果”,需要先去除文本中的逗号和非数字内容,再转换为数值类型(比如long)才能进行大小比较。断言逻辑设置
无需使用assertEquals,改用Assert.assertTrue()判断实际数值是否大于预期的5000。断言通过后直接执行打印语句即可输出"pass"。添加元素等待
搜索结果加载需要时间,直接定位元素容易触发NoSuchElementException,因此要添加显式等待确保元素加载完成。
修正后的完整代码
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; import org.junit.Assert; public class Grabthe_result_google { public static void main(String[] args) { ChromeOptions options = new ChromeOptions(); options.addArguments("--remote-allow-origins=*"); // 配置ChromeDriver路径(请根据实际路径调整) System.setProperty("webdriver.chrome.driver", "C:\\Users\\l\\OneDrive\\Desktop\\chromedriver-win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(options); driver.get("https://www.google.com"); // 执行搜索操作 driver.findElement(By.id("APjFqb")).sendKeys("mobile", Keys.ENTER); // 显式等待结果统计元素加载完成 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement resultStats = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result-stats"))); // 提取并处理结果数值 String resultText = resultStats.getText(); String numericPart = resultText.split(" ")[1].replace(",", ""); long actualResult = Long.parseLong(numericPart); System.out.println("搜索结果数量:" + actualResult); // 断言数值大于5000,通过则打印pass long expectedMinValue = 5000; Assert.assertTrue("结果数值未大于5000", actualResult > expectedMinValue); System.out.println("pass"); // 关闭浏览器 driver.quit(); } }
关键代码说明
- 显式等待:
WebDriverWait配合ExpectedConditions.visibilityOfElementLocated确保result-stats元素可见后再操作,避免元素未加载导致的异常。 - 数值转换:用
replace(",", "")去掉数字中的千位分隔符,再转成long类型(避免整数溢出)。 - 断言与打印:
Assert.assertTrue()可传入断言失败时的提示信息,断言通过后执行System.out.println("pass");若断言失败会抛出AssertionError,后续打印语句不会执行。
内容的提问来源于stack exchange,提问作者Pooja Shinde
相关产品推荐
相关产品推荐

