如何使用Selenium Webdriver从以下div获取文本

use*_*482 1 java selenium selenium-webdriver

我试图获取以下2个div元素中的项目的文本内容,但得到一个错误,该元素无法找到.例如,第一个div的文本内容是"Text1".我怎么能得到那个文字?

到目前为止,我尝试过:

driver.findElement(By.xpath("//*[@id='ctrlNotesWindow']/div[3]/ul/div[1]/div[2]/div[2]")).getText())
Run Code Online (Sandbox Code Playgroud)

而且抱怨没有找到那个元素.

这是html代码:

<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>
Run Code Online (Sandbox Code Playgroud)

这是错误,我得到:

线程"main"中的异常org.openqa.selenium.NoSuchElementException:无法定位元素:{"method":"xpath","selector":"//*[@ id ='ctrlNotesWindow']/div [3]/UL/DIV [1]/DIV [2]/DIV [2]"}

Yi *_*eng 9

不要使用无意义的XPath.您的错误消息告诉您"NoSuchElement",因此您的定位器错误,这与getText(尚未)无关.尝试使用CssSelector或有意义的XPath:

 driver.findElement(By.cssSelector("#ctrlNotesWindow .notesData > .notesDate")).getText();
Run Code Online (Sandbox Code Playgroud)


Mar*_*lle 6

如果出于某种原因你想坚持使用 Xpath:

driver.findElement(By.xpath("//div[@class='notesData']/div[@class='notesDate']")).getText();
Run Code Online (Sandbox Code Playgroud)

否则,上面的 css 选择器答案是一个不错的选择。

另一种选择是通过类名来定位元素:

driver.findElement(By.className("notesDate")).getText();
Run Code Online (Sandbox Code Playgroud)