How to retrieve text from an element using Seleniu

2019-08-02 04:13发布

问题:

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

回答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());