1

I'm trying to retrieve text of an element with == $0. I tried to use JS injection ((JavascriptExecutor) driver).executeScript("return arguments[0].value", driver.findElement(By.cssSelector("div.settings span"))) but this approach returns NULL for me enter image description here

Denis S.
  • 451
  • 1
  • 5
  • 19
  • Can you check in developer console how many entries are present with locator `div.settings span` ? – cruisepandey Apr 16 '19 at 04:58
  • Can you try this , let me know if this works ? `WebElement myElement = driver.findElement(By.cssSelector("div.settings span")); String myText = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", myElement); System.out.println(myText);` – cruisepandey Apr 16 '19 at 04:59
  • @DenisS. You don't retrieve the CSS path as such, rather you use CssSelector to identify elements. Are you are trying to retrieve any text? – undetected Selenium Apr 16 '19 at 07:39
  • @cruisepandey Seems the `` within the comments clearly says **Avoid answering questions in comments**. Comments are not useful as answers. Please take care. – undetected Selenium Apr 16 '19 at 07:41
  • @DebanjanB : OP is not clear, so it's always better to give alternate solution in case if it works. Need more info. – cruisepandey Apr 16 '19 at 09:20
  • Incase the question is not clear the correct approach is to ask for more information ... right? But not to answer within comments ... agree? – undetected Selenium Apr 16 '19 at 09:22
  • 1
    @cruisepandey, ```div.settings span``` locates one entry [span.label] – Denis S. Apr 16 '19 at 14:37
  • 1
    @DebanjanB, sorry, yes, i'm trying to get the text. I expect to get back ```shooting``` and ```pedestrian accident``` – Denis S. Apr 16 '19 at 14:38
  • Which text are you trying to extract? – undetected Selenium Apr 16 '19 at 14:40
  • 2
    @cruisepandey, the following script ```WebElement myElement = driver.findElement(By.cssSelector("div.settings span")); String myText = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", myElement); System.out.println(myText);``` returns only ```OR```. But i need to get ```shooting``` and ```pedestrian accident``` – Denis S. Apr 16 '19 at 14:42
  • 1
    DebanjanB, ```shooting``` and ```pedestrian accident``` – Denis S. Apr 16 '19 at 14:50

1 Answers1

1

As the texts Shooting and Pedestrian Accident are within elements which are text nodes, so to extract the texts you can use the following solutions:

WebElement myElement = driver.findElement(By.cssSelector("div.settings")); 
//extracting Shooting
System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", myElement).toString());
//extracting Pedestrian Accident
System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", myElement).toString());
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352