如何从Selenium(Java)抓取文本?

时间:2020-07-28 19:42:20

标签: java html selenium

我正在尝试从以下HTML代码中获取文本$ 1.00(我有xpath,所以不必担心)。为此,我们可以说xpath为// * [@@ id =“ price-string”]

<strong id="price-string">$1.00</strong>

我尝试过使用driver.findElement(By.xpath(“ // * [@ id =” price-string“]”)),然后使用.gettext()、. getAttribute(“ textContent”)、. getAttribute( “ innerHTML”);

所有人都返回null,这意味着他们找不到它。

我在stackexchange上看到了这篇文章:https://sqa.stackexchange.com/questions/30627/how-to-get-text-under-strong-tag-in-selenium-webdriver-using-java可能会有所帮助。他们说问题是,您不能使用Selenium WebDriver直接定位/查找文本节点,而只能使用常规元素节点。您将如何在Java中实现修复?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试下面的代码-

Thread.sleep(2000);
String word = driver.findElement(By.xpath("//strong[@id='price-string']")).getText();
System.out.println(word);

注意-如果这是您要寻找的,请标记为答案。