首页 > 解决方案 > 如何使用Java(用于硒自动化)获取段落标签内的文本。(div/div/p)

问题描述

我正在尝试使用 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>但没有得到它,但我可以使用 get tag name 函数获取标签名称。

标签: javaseleniumxpathcss-selectorswebdriverwait

解决方案


要提取文本We could not find that ... 或 password因为元素位于模态对话框中,您需要为visibilityOfElementLocated引入WebDriverWait,您可以使用以下任一解决方案:

  • 选择器

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

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

推荐阅读