使用带有 JavaScript 的 Selenium WebDriver 从位于 XPath 的元素中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18637032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text from XPath located Element using Selenium WebDriver with JavaScript
提问by Manu K Mohan
I am trying to find an element using xpath and get the elements text value.
我正在尝试使用 xpath 查找元素并获取元素文本值。
For example, I can find the element using xpath in the following way
例如,我可以通过以下方式使用 xpath 查找元素
driver.findElement(webdriver.By.xpath("//div/span));
But I want to get the text of this particular element by using JavaScript.
但是我想通过使用 JavaScript 来获取这个特定元素的文本。
HTML content is like below
HTML 内容如下
<div><span>Inner Text</span></div>
采纳答案by Nathan Merrill
The function you want is getText()
.
你想要的功能是getText()
.
String text = driver.findElement(webdriver.By.xpath("//div/span")).getText();
回答by ShaBANG
const By = webdriver.By;
driver.findElement(By.xpath('//div/span'))
.then(span => span.getText())
.then(text => console.log(text))
Most of the actions in the webdriver for node/'javascript' return a promise, you have to do a .then to actually get the values.
webdriver 中用于 node/'javascript' 的大多数操作都会返回一个 promise,您必须执行 .then 才能实际获取值。
回答by Puneet Sharma
WebDriver driver;
String getText = driver.findElement(By.xpath("your xpath")).getText();
This will return the text within that element.
这将返回该元素中的文本。
回答by Cute Developer
var element = driver.findElement(By.xpath("xpath")).getText();
console.log(element);
Not tested, but this will do.
没有经过测试,但这会做。