javafirefoxseleniumselenium-webdriver

Selenium WebDriver Finding Element by Partial Class Name


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?


Solution

  • 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();