1

This is sort of how looks (See below).I want to save the text "Page 1 to 20" in a string variable for later use.

This is what I did: string numOfPages = driver.FindElement(By.XPath("//*[@id='tabletransaction']/text()")).Text;

i´ve tried in multiple ways but as the result is an [Object Text] it don´t work as it needs to be an element.

<div id="tabletransaction">
    <table id ="ticketransaction">
        <thead><tr><th>Some text</th></tr></thead>
        <thead><tr><th>Some text</th></tr></thead>
        <thead><tr><th>Some text</th></tr></thead>
        <thead><tr><th>Some text</th></tr></thead>
    </table>

    Page 1 to 20
</div>
budi
  • 6,351
  • 10
  • 55
  • 80
jaikl
  • 971
  • 2
  • 9
  • 23
  • maybe text is not an element and it cannot be an element? element here is a `div` which contains text – Sergey Berezovskiy Jun 27 '17 at 14:49
  • I know that, but how can i fetch the text. If i try to do that direclty on the div tag all the text including all the text are retrived – jaikl Jun 27 '17 at 14:53
  • Possible duplicate of [How to get text from parent element and exclude text from children (C# Selenium)](https://stackoverflow.com/questions/28945692/how-to-get-text-from-parent-element-and-exclude-text-from-children-c-selenium) – Kirhgoph Jun 27 '17 at 15:06

1 Answers1

1

You need to remove /text() from your XPath:

Your xpath doesn't return an element; it returns a text node. While this might have been perfectly acceptable in Selenium RC (and by extension, Selenium IDE), the methods on the WebDriver WebElement interface require an element object, not just any DOM node object. WebDriver is working as intended. To fix the issue, you'd need to change the HTML markup to wrap the text node inside an element, like a <span>.

Reference: https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5459#issuecomment-192110781

NOTE: Unfortunately, if you remove /text() from the XPath, you will now be selecting the text of the entire element. Without any selectors wrapped around the "Page 1 to 20" text, it is not possible to just "select" this text.


Here's a naive way to solve your specific problem:

Select the <div>.Text and the <table>.Text, then subtract (string.Replace) the <table>.Text from the <div>.Text:

// "Some text\r\nSome text\r\nSome text\r\nSome text\r\nPage 1 to 20"
string divText = Driver.FindElement(By.Id("tabletransaction")).Text;

// ""Some text\r\nSome text\r\nSome text\r\nSome text"
string tableText = Driver.FindElement(By.Id("ticketransaction")).Text;

// "Page 1 to 20"
string remainingText = divText.Replace(tableText, string.Empty).Trim();
budi
  • 6,351
  • 10
  • 55
  • 80