0
<dd>
::before
<strong>Test Date:</strong>
"
7/6/20 - Monday"
::after
</dd>

the above is the sample html.

I want to locate the date which is after "Test Date:" Since there will be many dates in the page, I want to locate the date with reference to the text "Test Date:" How do I write xpath for this requirement? or using any other locator.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217

2 Answers2

0

It is not enough to write xpath (which in your case would be //dd/strong[text()='Test Date:']/following-sibling::text()[1]). You need a separate text node which cannot be treated by Selenium as a web element. Use IJavaScriptExecutor:

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string dateText = (string)js.ExecuteScript("return document.evaluate(\"//dd/strong[text()='Test Date:']/following-sibling::text()[1]\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.cloneNode(true).text;");
Alexey R.
  • 4,490
  • 1
  • 7
  • 22
0

The text 7/6/20 - Monday is within a text node of the parent <dd> node. So to extract the date which is just after Test Date: you can use the following based Locator Strategy:

IWebElement element = driver.FindElement(By.XPath("//dd[./strong[text()='Test Date:']]"));
string text = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].childNodes[3].textContent;", element);

References

You can find a couple of relevant discussions in:

DebanjanB
  • 118,661
  • 30
  • 168
  • 217