如何使用Selenium WebDriver和Java从元素检索文本
问题描述:
我正尝试使用== $ 0检索元素的文本.我尝试使用JS注入
((JavascriptExecutor) driver).executeScript("return arguments[0].value", driver.findElement(By.cssSelector("div.settings span")))
但是这种方法为我返回NULL
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
答
由于文本射击和行人事故属于文本节点,因此要提取文本,可以使用以下解决方案:
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());