简体   繁体   中英

How to get a text from following div using Selenium Webdriver

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]"}

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();

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();

It works with:

driver.findElement(By.xpath("//div[@class='ui-pnotify-text']")).getText();

which is an PNotify notification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM