-1

Below is the element and I need to find the class names matching with the first css- and ending with widget, How do i find it in selenium (java)?

Tried with the below code, but it didnt work

List<WebElement> list1 = driver.findElements(By.xpath("//body[starts-with(@class, 'css-')]"));
List<WebElement> list2 = driver.findElements(By.xpath("//body[contains(@class, 'css-')]"));
List<WebElement> list3 = driver.findElements(By.xpath("//body[ends-with(@class, 'widget')]"));
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
prav kum
  • 424
  • 3
  • 7
  • 22
  • What does "it didn't work" mean? Post your error messages or explain how it didn't achieve what you wanted. Is there an actual `BODY` HTML tag that hold these partial class names or is it some other HTML tag? If you are looking for any tag, swap `*` for `BODY`, e.g. `//*[starts-with(@class, 'css-')]`. – JeffC Jan 31 '19 at 13:35

2 Answers2

4

I use CSS selectors, to find any element of any type:

driver.findElements(By.CssSelector("[class^='css-'][class$='widget']"))

Where we find any element, which has a class attribute using [], that begins with ^= and ends with $=

To find a div:

driver.findElements(By.CssSelector("div[class^='css-'][class$='widget']"))

elworthy
  • 454
  • 4
  • 12
1

@elworthy's answer was in the right direction about the CssSelector which you can use and as per your code trials the following should work:

List<WebElement> list3 = driver.findElements(By.CssSelector("//body[class^='css-'][class$='widget']"));

However if you want to construct a xpath it is worth to mention Selenium supports xpath v1.0 and ends-with() is part of xpath v2.0. So the equivalent xpath will be:

List<WebElement> list1 = driver.findElements(By.xpath("//body[starts-with(@class, 'css-') and contains(@class, 'widget')]"));
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352