Reputation: 75
I am trying to get the text content of the items inside the following 2 div elements but getting an error that the element cannot be found. For example the text content for first div is "Text1". How can I get that text?
So far, I have tried:
driver.findElement(By.xpath("//*[@id='ctrlNotesWindow']/div[3]/ul/div[1]/div[2]/div[2]")).getText())
and that complains of not finding that element.
Here is the html code:
<div class="notesData">
<div class="notesDate" data-bind="text: $.format('{0} - {1}', moment(Date).format('MMM DD, YYYY h:mm a'), User)">Text1</div>
<div class="notesText" data-bind="text: Note">Text2 on next line</div>
</div>
Here is the error, I get:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[@id='ctrlNotesWindow']/div[3]/ul/div[1]/div[2]/div[2]"}
Upvotes: 3
Views: 98077
Reputation: 32855
Don't use meaningless XPath. Your error message tells you "NoSuchElement", so you had your locator wrong, which has nothing to do with getText (not yet). Try using CssSelector or meaningful XPath:
driver.findElement(By.cssSelector("#ctrlNotesWindow .notesData > .notesDate")).getText();
Upvotes: 11
Reputation: 1659
It works with:
driver.findElement(By.xpath("//div[@class='ui-pnotify-text']")).getText();
which is an PNotify notification.
Upvotes: 1
Reputation: 918
If for whatever reason you'd want to stick with Xpath:
driver.findElement(By.xpath("//div[@class='notesData']/div[@class='notesDate']")).getText();
Otherwise, the css selector answer above is a good option.
Another alternative is to locate the element by class name:
driver.findElement(By.className("notesDate")).getText();
Upvotes: 6