0

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?

4 Answers 4

1

You can use xpath

span = driver.findElement(By.id("lblName"));
div = span.findElement(By.xpath(".."));
Sign up to request clarification or add additional context in comments.

2 Comments

I am not sure why, but I am not able to locate the element by id
Found that iframe was causing the element not to be found
1

You can try: //span[@id = 'lblName']/parent::div/text()

Comments

0

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;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.