【问题标题】:Using Selenium and Java How to ignore part of an element in xpath使用 Selenium 和 Java 如何忽略 xpath 中的部分元素
【发布时间】:2022-01-27 17:58:55
【问题描述】:

我有以下方法:

protected String getCertID() {
    String certIDKey = "certID";
    TestAction action = new TestAction(ActionType.SET_ELEMENT_TEXT,springContext);

    action.setIdentifierType("xpath");
    action.setIdentifierValue("//h1[contains(@data-id,'header_title')]");
    action.setValue(certIDKey);

    action.perform(driverFactory,testContext);

    log.info("CertID: " + testContext.getVariable(certIDKey));
    return testContext.getVariable(certIDKey);
}

此方法的输出:21/2/467092- 已保存

我要求该方法仅返回:21/2/467092 并忽略 - 返回的元素的已保存部分

【问题讨论】:

    标签: java selenium


    【解决方案1】:

    如果h1 包含子元素,例如一些span 元素,以及您想要放置在某个子元素中的确切文本,例如:

    <h1 data-id="header_title">
        <span id="date">21/2/467092</span>
        <span>- Saved</span>
    </h1>
    

    你可以使用

    "//h1[contains(@data-id,'header_title')]/span[1]"
    

    "//h1[contains(@data-id,'header_title')]/span[@id='date']"
    

    否则,对于情况:

    <h1 data-id="header_title">21/2/467092- Saved</h1>
    

    <h1 data-id="header_title">
        21/2/467092
        <span>- Saved</span>
    </h1>
    

    你只能调整h1的结果文本

    ...
    String roughText = testContext.getVariable(certIDKey);
    return roughText.split("-")[0].trim();
    

    【讨论】:

    • 感谢您的回复。我发现: //*[@id="formHeaderTitle_0"]/text() 似乎找到了我需要的正确部分,但是在方法中运行它会导致测试失败。上面建议的这一行 "//h1[contains(@data-id,'header_title')]/span[1]" 只返回我不需要的部分,并且找不到上面的这一行 //h1[contains(@data -id,'header_title')]/span[@id='date']
    • 试试//*[@id="formHeaderTitle_0"],不试试/text()
    • NULL 返回的“文本”必须是证书参考号
    • 抱歉,/span[1]/span[@id='date'] 只是示例,基于我对您页面外观的假设,因为我看不到真正的 HTML 页面源代码。
    • 另外,我看到您提供的代码示例背后发生了一些事情。目前还不清楚testContext 是什么。我看到你对它执行的操作,然后你得到了变量。但我看不到执行了什么硒代码。我假设您在某些 WebElement 上调用 getText() 方法,但没有详细信息。
    【解决方案2】:

    如果 "- Saved" 在那里不变,您可以将其替换为 ""

    protected String getCertID() {
      String certIDKey = "certID";
      TestAction action = new TestAction(ActionType.SET_ELEMENT_TEXT,springContext);
    
      action.setIdentifierType("xpath");
      action.setIdentifierValue("//h1[contains(@data-id,'header_title')]");
      action.setValue(certIDKey);
    
      action.perform(driverFactory,testContext);
    
      log.info("CertID: " + testContext.getVariable(certIDKey));
    return testContext.getVariable(certIDKey).replace("- Saved", "");
    }
    

    【讨论】:

    • 我曾尝试使用此功能,但在使用此功能时出现错误“action.setValue(certIDKey); unreachable statement”
    • 尝试复制并粘贴更新后的代码
    • 我已经更新了上面的帖子,谢谢 action.setValue(certIDKey); = 无法访问的语句
    • 只用我的return语句替换你,不要在你的方法中写2 return,它会运行,java防止你编写jvm无法执行的代码“无法访问的代码”跨度>
    • 当然是的,我已经更改了它,返回的值仍然包含 -saved 我已经编辑了上面的代码作为参考谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2022-12-03
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多