Selenium WebDriver 按部分类名查找元素 [英] Selenium WebDriver Finding Element by Partial Class Name

查看:27
本文介绍了Selenium WebDriver 按部分类名查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用的框架中,我有以下元素:

来自客户端 IP 192.168.5.3 (ST=/CC=/C=) 的新会话位于 VIP 192.168.5.2 Listener/Common/Tomcat (Reputation=Unknown)</div>

以及许多其他类似的元素.我正在尝试通过部分名称文本定位此元素并使用以下代码单击它:

String expectedText = "来自客户端 IP 的新会话";driver.findElement(By.className("div[class*='"+expectedText+"']")).click();

而且我也尝试过使用 cssSelector:

String expectedText = "来自客户端 IP 的新会话";driver.findElement(By.cssSelector("div[class*='"+expectedText+"']")).click();

但 WebDriver 不断抛出异常,指出它无法定位该元素.关于可能是什么问题的任何建议?

解决方案

By.className 正在寻找输入名称的类.

By.cssSelector 正在为您输入的选择器寻找匹配项.

您正在尝试将 div 的文本与 class 进行匹配,但这是行不通的.

你可以试试这样的:

driver.findElement(By.xpath("//div[contains(text(),'"+expectedText+"')]")).click();

In the frame I'm working with, I have the following element:

<div class="x-grid3-cell-inner x-grid3-col-expRepCol">  New session from client IP 192.168.5.3 (ST=/CC=/C=) at VIP 192.168.5.2 Listener /Common/Tomcat (Reputation=Unknown)</div>

As well as many other similar elements. I am trying to locate this element by partial name text and click it with the following code:

String expectedText = "New session from client IP";
driver.findElement(By.className("div[class*='"+expectedText+"']")).click();

And I have also tried with cssSelector:

String expectedText = "New session from client IP";
driver.findElement(By.cssSelector("div[class*='"+expectedText+"']")).click();

But WebDriver keeps throwing an exception stating it's unable to locate that element. Any suggestions as to what could be the problem?

解决方案

By.className is looking for a class with the name entered.

By.cssSelector is looking for a match for the selector you entered.

What you're attempting is to match the text of the div against class, which won't work.

You can try something like this:

driver.findElement(By.xpath("//div[contains(text(),'"+expectedText+"')]")).click();

这篇关于Selenium WebDriver 按部分类名查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆