Reputation: 1169
I would like to get the text of <div>
element.
The only thing I am able to use is <span>
element inside this <div>
.
<div>
<span id="lblName" class="fieldTitle">Name</span>
John
</div>
How can I receive John
using lblName
or Name
?
Upvotes: 0
Views: 1926
Reputation: 5127
You cannot get the text node by Selenium. Please try the workaround with JS below:
IWebElement span = driver.FindElement(By.Id("lblName"));
IWebElement div = span.FindElement(By.XPath(".."));
string script = "var nodes = arguments[0].childNodes;" +
"var text = '';" +
"for (var i = 0; i < nodes.length; i++) {" +
" if (nodes[i].nodeType == Node.TEXT_NODE) {" +
" text += nodes[i].textContent;" +
" }" +
"}" +
"return text;";
string text = driver.GetJavaScriptExecutor().ExecuteScript(script, div).ToString();
Upvotes: 0
Reputation: 737
Something like this:
string xml = "<?xml version=\"1.0\"?>" +
"<div>" +
"<span id=\"lblName\" class=\"fieldTitle\">Name</span>" +
"</div>";
XDocument xdoc = XDocument.Parse(xml);
var parent = xdoc.Descendants().First(el => el.Name == "span" &&
el.Attribute("id") != null &&
el.Attribute("id").Value == "lblName").Parent;
Upvotes: 0
Reputation: 1342
You can use xpath
span = driver.findElement(By.id("lblName"));
div = span.findElement(By.xpath(".."));
Upvotes: 1