如何使用 Selenium 检查页面中是否存在某些文本? [英] How can I check if some text exist or not in the page using Selenium?
问题描述
我正在使用 Selenium WebDriver,如何检查页面中是否存在某些文本?也许有人向我推荐了有用的资源,我可以在其中阅读它.谢谢
I'm using Selenium WebDriver, how can I check if some text exist or not in the page? Maybe someone recommend me useful resources where I can read about it. Thanks
推荐答案
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));
这篇关于如何使用 Selenium 检查页面中是否存在某些文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!