如何使用Selenium WebDriver验证元素中是否存在属性? [英] How to verify an attribute is present in an element using Selenium WebDriver?

查看:817
本文介绍了如何使用Selenium WebDriver验证元素中是否存在属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的屏幕上有很多单选按钮。选择单选按钮时,它具有已检查的属性。未选择单选按钮时,不存在checked属性。我想创建一个方法,如果该元素不存在将通过。

I have many radio buttons on my screen. When a radio button is selected, it has an attribute of checked. When the radio button is not selected, the checked attribute is not present. I would like to create a method that would pass if the element is not present.

我使用的是selenium webdriver和java。我知道我可以使用 getSingleElement(XXX).getAttribute(XXX)来检索属性。我只是不确定如何验证属性不存在,以及测试在不存在时通过(如果确实存在则失败)。

I am using selenium webdriver and java. I know I can retrieve attributes by using getSingleElement(XXX).getAttribute(XXX). I'm just not sure how to verify that an attribute does not exist, and for the test to pass when it doesn't exist (fail if it does exist).

选中单选按钮时

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1" checked="checked"> 

未选中单选按钮时

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1">

我希望测试在check属性不存在时通过

I want the test to pass when the checked attribute is not present

推荐答案

您可以创建一个正确处理它的方法。请注意以下是C#/ Java混合样式,需要稍微调整一下才能编译。

You can create a method to handle it properly. Note this following is in C#/Java mixed style, you need to tweak a bit to compile.

private boolean isAttribtuePresent(WebElement element, String attribute) {
    Boolean result = false;
    try {
        String value = element.getAttribute(attribute);
        if (value != null){
            result = true;
        }
    } catch (Exception e) {}

    return result;
}

如何使用它:

WebElement input = driver.findElement(By.cssSelector("input[name*='response']"));
Boolean checked = isAttribtuePresent(input, "checked");
// do your assertion here

这篇关于如何使用Selenium WebDriver验证元素中是否存在属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆