使用 Selenium 2 查找页面上的文本
如何使用 Selenium 检查当前页面上是否存在给定的文本字符串?
How can I check whether a given text string is present on the current page using Selenium?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
代码是这样的:
The code is this:
如果您在整个页面中搜索某些文本,则无需提供
xpath
或选择器
来查找元素。以下代码可能会有所帮助..If your searching the whole page for some text , then providing an
xpath
orselector
to find an element is not necessary. The following code might help..由于某种原因,某些元素似乎不响应其他答案中列出的“通用”搜索。至少不在 Robot Framework 下的 Selenium2library 中,这是我需要这个咒语来查找特定元素的地方:
For some reason, certain elements don't seem to respond to the "generic" search listed in the other answer. At least not in Selenium2library under Robot Framework which is where I needed this incantation to find the particular element:
XPath 的一个更简单(但可能效率较低)的替代方案是获取页面正文中的所有可见文本,如下所示:
然后,如果您使用 JUnit 或其他东西,您可以使用断言来检查您正在搜索的字符串包含在其中。
使用 XPath 可能更有效,但对于不熟悉它的人来说,这种方式更容易理解。此外,由
assertThat
生成的AssertionError
将包含页面上确实存在的文本,这可能有利于调试,因为任何查看日志的人都可以清楚地看到文本是什么如果我们正在寻找的内容不在页面上。A simpler (but probably less efficient) alternative to XPaths is to just get all the visible text in the page body like so:
Then if you're using JUnit or something, you can use an assertion to check that the string you are searching for is contained in it.
Using an XPath is perhaps more efficient, but this way is simpler to understand for those unfamiliar with it. Also, an
AssertionError
generated byassertThat
will include the text that does exist on the page, which may be desirable for debugging as anybody looking at the logs can clearly see what text is on the page if what we are looking for isn't.