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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20386581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:34:26  来源:igfitidea点击:

How to get a text from following div using Selenium Webdriver

javaseleniumselenium-webdriver

提问by user2250482

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?

我正在尝试获取以下 2 个 div 元素中项目的文本内容,但出现无法找到该元素的错误。例如第一个 div 的文本内容是“Text1”。我怎样才能得到那个文本?

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:

这是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>

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

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

采纳答案by Yi Zeng

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:

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

 driver.findElement(By.cssSelector("#ctrlNotesWindow .notesData > .notesDate")).getText();

回答by Marielle

If for whatever reason you'd want to stick with Xpath:

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

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

Otherwise, the css selector answer above is a good option.

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

Another alternative is to locate the element by class name:

另一种选择是按类名定位元素:

driver.findElement(By.className("notesDate")).getText();

回答by Angel Cuenca

It works with:

它适用于:

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

which is an PNotify notification.

这是一个 PNotify 通知。