java - 如何在java中使用selenium获取包裹在段落元素<p>中的文本值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43652975/
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-11-03 07:38:20  来源:igfitidea点击:

how to get value of text wrapped in paragraph element <p> with selenium in java

javaseleniumxpath

提问by Prasad_Joshi

I have a button, clicking on it generates a number which is wrapped in paragraph text such as <p>random number <p>, I want to get that random number value and do operations based on number it generates. From below I need to get 34,756number and store it in java here is the html code for it:

我有一个按钮,单击它会生成一个包含在段落文本中的数字,例如<p>random number <p>,我想获取该随机数值并根据它生成的数字执行操作。从下面我需要获取34,756数字并将其存储在 java 中,这是它的 html 代码:

<div class="form-group">
<div class="alert alert-count">
  <p>
  <b>
<!-- react-text: 531 -->
<!-- /react-text -->
<!-- react-text: 532 -->
 34,756
<!-- /react-text -->
</b>

and the xpath I used is as below

我使用的xpath如下

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p[1]/b).getText();

but on console it gives error as

但在控制台上它给出了错误

Exception in thread "main" java.lang.NullPointerException

线程“main”中的异常 java.lang.NullPointerException

回答by kushal.8

Try using following:

尝试使用以下方法:

  String count = driver.findElement(By.cssSelector("div.alert.alert-count p")).getText();

回答by Jainish Kapadia

Try this below code using xpath locator

使用下面的代码试试这个 xpath locator

String element = driver.findElement(By.xpath("//div[@class='alert alert-count']/p/b")).getText();
System.out.println(element);

Explanation of xpath:-Use classattribute of <div>tag and move ahead with <p>and <b>tag.

xpath 的解释:-使用标签的class属性<div>并使用<p><b>标签前进。

回答by shinde suraj

Try this below code using XPath locator

使用 XPath 定位器试试下面的代码

String element = driver.findElement(By.xpath("//div[@class='alert alert-count']")).getText();
System.out.println(element);