-1

I need to access this text in the picture. I am using VB.NET and I need to show me in a MessageBox. The sentence is: "My friend is going to watch a film in cinema but there is no tickets.". When I right click on this and get the full Xpath, it shows me this:

/html/body/div[7]/div[3]/div/div[2]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div/div[9]/div/div[1]/div[2]/div/table/tbody/tr[1]/td[4]/div[1]/text()[4]

So this is the code I use in VB.NET:

MsgBox(driver.FindElement(By.XPath("/html/body/div[7]/div[3]/div/div[2]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div/div[9]/div/div[1]/div[2]/div/table/tbody/tr[1]/td[4]/div[1]/text()[4]")))

But I get following error:

OpenQA.Selenium.InvalidSelectorException: 'invalid selector: The result of the xpath expression "/html/body/div[7]/div[3]/div/div[2]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div/div[9]/div/div[1]/div[2]/div/table/tbody/tr[1]/td[4]/div[1]/text()[4]" is: [object Text]. It should be an element.

enter image description here

James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

1

This error message...

OpenQA.Selenium.InvalidSelectorException: 'invalid selector: The result of the xpath expression "/html/body/div[7]/div[3]/div/div[2]/div[2]/div/div/div/div/div[2]/div/div1/div/div/div[9]/div/div1/div[2]/div/table/tbody/tr1/td[4]/div1/text()[4]" is: [object Text]. It should be an element.

...implies that the xpath:

/html/body/div[7]/div[3]/div/div[2]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div/div[9]/div/div[1]/div[2]/div/table/tbody/tr[1]/td[4]/div[1]/text()[4]

returned an `[object Text] which isn't supported by Selenium. Where as Selenium expects a WebElement.


Solution

To extract the text from the 4th Text Node and show in a MessageBox you need to use the ExecuteScript() method as follows:

MsgBox((string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].lastChild.textContent;" driver.FindElement(By.XPath("//td[@class='yX Yx' and @role='gridcell']/div")))
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

I found the solution:

MsgBox(driver.FindElement(By.XPath("/html/body/div[7]/div[3]/div/div[2]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[1]/div[9]/div/div[1]/div[2]/div/table/tbody/tr[1]/td[4]/div[1]")).GetAttribute("innerHTML"))

It will retrieve whole texts.