1

I am writing an automation application for a Website. Therefore I need to steer on HTML Elements, which don't have a ID. I heard that xPath and CSS Selector are not that fastest, that's why I want to change to By.className(). Unfortunately I this isn't working. You can find a Demo (the actual tool is not automating google :D) below.

I am using a GeckoDriver 0.21.0 and Selenium 3.13.0

WebDriver d = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor) d;  
d.get("https://www.google.com");
WebElement we = d.findElements(By.className("gLFyf gsfi")).get(0);
js.executeScript("arguments[0].value='test';", we);

HTML Element

Brian
  • 5,069
  • 7
  • 37
  • 47
  • seems like there are no elements with that specific class name returned – Talik Feb 25 '19 at 19:24
  • What makes you think that `By.className()` is faster than CSS selectors? Where did you see that CSS selectors aren't fast? "Isn't working" isn't very descriptive. Edit your question and post the actual error message. You question title isn't a question... you should fix that too. – JeffC Feb 25 '19 at 19:48
  • 1
    One error you are going to run into is that "gLFyf gsfi" is not a class name... it's actually two class names, "gLFyf" and "gsfi", so you can't use it in `By.className()` or you will get an error about compound class names. You will have to pick one or the other or use a CSS selector, `By.cssSelector(".gLFyf.gsfi")`. – JeffC Feb 25 '19 at 19:49

2 Answers2

1

If that class name is correct and stable (it looks generated to me, meaning there would be a different class name every time you load the page, a change that would break your script), I would recommend using

WebElement we = d.findElements(By.cssSelector(".gLFyf.gsfi")).get(0);

As indicated in another answer, By.className() is probably confused by the space in your class name.

C. Peck
  • 3,641
  • 3
  • 19
  • 36
-1

First, lemme address the claim "xPath and CSS Selector are not that fastest". They are slower by nanoseconds, and maybe! Have a read here if you are interested in more information.

Next your actual problem. The class attribute in HTML, is a space-separated list of class names. In your By.className() you can use only one of those.

Also, you are using .findElements() (the plural form), and expecting only a single WebElement. The compiler will probably tell you that you should be expecting List<WebElement>. Then in your .executeScript() this obviously will not work, as that is again expecting only one element. You will have to resolve what do you actually want here.

SiKing
  • 10,003
  • 10
  • 39
  • 90