How to get text from a div tag?

Viewed 90

I am trying to get text from div and put it in a text document using selenium c#. I cant seem to capture the text from div in variable

<div data-tid="messageContent" dir="auto"><div>new doc</div></div>

I tried these:

var puttingDataInDoc = driver.FindElement(By.XPath("//*[@data-tid='messageContent']")).GetAttribute();
var puttingDataInDoc = driver.FindElement(By.XPath("//*[@data-tid='messageContent']")).Text();
var puttingDataInDoc = driver.FindElement(By.XPath("//*[@data-tid='messageContent']")).Text;

Any suggestions please?

1 Answers

Text is a property, not method

var puttingDataInDoc = driver.FindElement(By.XPath("//*[@data-tid='messageContent']/div")).Text;

GetAttribute() needs a parameter specifying the attribute to fetch

var puttingDataInDoc = driver.FindElement(By.XPath("//*[@data-tid='messageContent']/div")).GetAttribute("textContent");
// or
var puttingDataInDoc = driver.FindElement(By.XPath("//*[@data-tid='messageContent']/div")).GetAttribute("innerHTML");

You should also target the child <div>, the text is there.

Related