简体   繁体   中英

How to get the text which is outside of a element and changes in the run time using selenium c#?

I have piece of code as below

<div class="span6" style="text-align:right;">
    <span class="muted" style="padding-left:20px;">Member ID: </span>MKL123451KKM
    <span class="muted" style="padding-left:20px;">Service Date: </span>05/08/2018
</div>

in above code i want to get the value " MKL123451KKM ", this value is going to change often.

i have tried with below xpaths which was giving error.

XPATH :

  1. /html/body/div/span[1][contains(text(),'Member ID:')]/../text()

  2. /html/body/div/span[1][contains(.,'Member ID:')]/../text()

ERROR :

The result of the xpath expression :

/html/body/div/span[1][contains(text(),'Member ID:')]/../text() is: [object Text]. It should be an element.

NOTE:

i am using selenium driver for IE and c# with VS 2015 IDE

Can anybody throw light on this?

As per the HTML you have shared the text MKL123451KKM is not within any child <span> node but within the parent <div> node. To extract the text eg MKL123451KKM you can use the following code block :

IWebElement elem = driver.FindElement(By.XPath("//div[@class='span6']"));
string text = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].childNodes[2].textContent;", elem);

You were fairly close. It's generally not a good practice to create a locator that starts at the HTML tag or has too many levels because it's more brittle (more likely to break when the page changes). Ideally you would find the label element by text label, eg "Member ID", and then locate the following text node. The big benefit of this method is that it's tied to the "Member ID" label. Some of the other answers are hard-coded to a specific text node which may be good now but if the data changes, it may return the wrong value.

You can wrap this all in a function where you pass in the label and it returns the value.

public string GetValue(string labelName)
{
    IWebElement e = Driver.FindElement(By.XPath($"//span[contains(.,'{labelName}')]"));
    string s = (string)((IJavaScriptExecutor)Driver).ExecuteScript("return arguments[0].nextSibling.textContent;", e);
    return s.Trim();
}

and you would call it like

GetValue("Member ID")

That's because the text is within the div. You will need to get text from xpath:

//div[@class='span6']

Even though this xpath isn't very change-proof, it should work if you get text from it. The text though will be MKL123451KKM and 05/08/2018

试试这个XPath

//div[@class='span6']/span/following-sibling::text()[1]

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