简体   繁体   中英

Selenium C# - Finding div elements text by span element in it

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 ?

You can use xpath

span = driver.findElement(By.id("lblName"));
div = span.findElement(By.xpath(".."));

您可以尝试: //span[@id = 'lblName']/parent::div/text()

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM