Reputation: 1640
Here are a few examples I have tried based on my past Python projects (here I am using JavaScript)...
var eltext = driver.findElement(webdriver.By.className('el')).text;
console.log(elname);
var eltext = driver.findElement(webdriver.By.className('el')).innerText;
console.log(elname);
var eltext = driver.findElement(webdriver.By.className('el')).innerHTML;
console.log(elname);
I have also tried a few other ways using String()
, JSON.stringify()
, and various for loops, spinning out on my options. I can do a .click()
and this object is clickable, so I know my selector is right, but the accessing the inner text in JavaScript is an issue.
Upvotes: 0
Views: 1521
Reputation: 151401
Here is how you can do it:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('http://www.example.com');
var el = driver.findElement(webdriver.By.tagName('div'));
// Get the text of the element using getText...
el.getText().then(function (text) {
console.log(text);
});
// The code above could be shortened to this:
// el.getText().then(console.log);
// Get the inner HTML of the element using getInnerHtml...
el.getInnerHtml().then(function (html) {
console.log(html);
});
// The code above could be shortened to this:
// el.getInnerHtml().then(console.log);
// Get the text browser side plus the innerHTML at the same time.
driver.executeScript('\
var el = arguments[0];\
return {text: el.innerText, html: el.innerHTML};\
', el).then(function (val) {
console.log(val.text);
console.log(val.html);
});
driver.quit();
You have to use .then
because the methods do not return the value itself but a promise to get the value.
The last method with executeScript
gets the two values at the same time. If you wonder why one would bother with executeScript
, the reason is that each call to getText
and getInnerHtml
means a round trip between the Selenium client (your script) and the Selenium server (the browser). On large test suites these round trips accumulate and can add minutes to the run time of the suite. I've also put it there to show that you can run any JavaScript you want on the browser by using this method.
Upvotes: 1
Reputation: 72261
You're dealing with a WebElement
from Selenium, not a DOM Element
, so don't attempt to use DOM API you know from the browser. Selenium is a different pair of shoes.
Selenium web driver docs point to getText()
or getInnerHtml()
.
Upvotes: 0