Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 461
user2150250 Avatar asked May 11 '26 08:05

user2150250


1 Answers

<div class="dd algo algo-sr Sr" data-937="5d1abd07c5a33">
<div class="dd algo algo-sr fst Sr" data-0ab="5d1abd837d907">

The above 2 are the HTML elements in yahoo search results. So if we wanna get these elements using a partial class name with selenium python, here is the solution.

# for selenium old version:
driver.find_element_by_css_selector("div[class^='dd algo algo-sr']")

# for selenium new version
driver.find_element(By.CSS_SELECTOR, "div[class^='dd algo algo-sr']")

In the same way, we can get any elements with a partial match on any attribute values like class name, id, etc.

find elements with css selector partial match on attribute values: find elements with css selector partial match on attribute values

like image 61
Ajeet Verma Avatar answered May 14 '26 00:05

Ajeet Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!