如何使用 Java(用于 selenium 自动化)获取段落标记内的文本。(div/div/p)

How to get the text inside a paragraph tag .(div/div/p) using Java(for selenium automation)

我正在尝试使用 xpath 从模型中获取文本,但最终没有得到任何文本,但我可以获取标签名称。

HTML:

<div class="modal fade custom-modal" id="loginfailure-modal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <p id="custom-modal-text">We could not find that<br> account. Incorrect email and /<br> or password</p>
                    <button id="custom-modal-btntext" type="button" class="button green-button custom-modal-button" data-dismiss="modal">Please try again</button>
                </div>
            </div>
        </div>
    </div>

代码试用:

String txt = driver.findElement(By.xpath("//p[@id='custom-modal-text']")).getText();

我想要 <p> 标签内的文本,但我没有得到它,但我可以使用获取标签名称函数获取标签名称。

要提取文本 我们无法找到...或密码,因为该元素位于 模态对话框 中,您需要为 visibilityOfElementLocated 引入 WebDriverWait,您可以使用以下任一解决方案:

  • cssSelector:

    String txt = driver.findElement(By.cssSelector("div.modal.fade.custom-modal#loginfailure-modal div.modal-body>p")).getText();
    
  • xpath:

    String txt = driver.findElement(By.xpath("//div[@class='modal fade custom-modal' and @id='loginfailure-modal']//div[@class='modal-body']/p")).getText();