且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Selenium 检查页面中是否存在某些文本?

更新时间:2023-11-25 22:21:46

With XPath,这并不难.只需搜索包含给定文本的所有元素:

With XPath, it's not that hard. Simply search for all elements containing the given text:

List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

官方文档不是很支持这样的任务,但它是基本工具尽管如此.

The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.

JavaDocs 更大,但需要一些时间来了解所有有用和无用的东西.

The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.

要学习 XPath,只需关注互联网.该规范也出奇地好读.

To learn XPath, just follow the internet. The spec is also a surprisingly good read.

或者,如果您不希望 隐式等待上面的代码等待文本出现,你可以这样做:

Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));