获取表单中的所有元素 [英] Get all Elements in a Form

查看:59
本文介绍了获取表单中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Selenium提交包含多个元素的表单.例如:

I would like to use Selenium to submit a form which contains several elements. For example:

<form name="something">
    <input type="text" name="a">Username</input>
    <input type="password" name="b">password</input>
    <select name="c" id="c">
       <option value="1">1</option>
       <option value="2">2</option>
    </select>
    <input type="submit" name="submit">submit</input>
</form>

如果我使用find.Element(By.name)来查找表单元素,那么如何获取其子元素a,b和c?并将值输入到这三个元素中,然后提交表单?

If I use find.Element(By.name) to find out the form element, how can I get its children elements a, b, and c? And input the values into these three elements then submit the form?

另一个类似的问题是:如果我得到元素 a ,如何获得元素 b c 的形式相同,并且先填写(或选择)值,然后提交表单?

Another similar question is: if I get the element a, how to get elements b and c are in the same form and to fill (or select) values first, then submit the form?

提前谢谢!

推荐答案

您可以使用xpath通过 parent/* 获取特定元素的所有直接子元素.

You can use xpath to get all direct child elements of a specific element using parent/*.

如果您已经使用 findElement()使用了 form 元素,如下所示:

If you already have your form element using findElement(), as below:

WebElement formElement = driver.findElement(By.name("something"));
List<WebElement> allFormChildElements = formElement.findElements(By.xpath("*"));

或直接使用:

List<WebElement> allFormChildElements = driver.findElements(By.xpath("//form[@name='something']/*"));

然后查看每个元素的标签和类型以指定其值:

Then look at the tag and type of each element to specify its value:

for (WebElement item : allFormChildElements)
{
    if (item.getTagName().equals("input"))
    {
        switch (item.getAttribute("type"))
        {
            case "text": 
                //specify text value
                break;
            case "checkbox":
                //check or uncheck
                break;
            //and so on
        }
    }
    else if (item.getTagName().equals("select"))
    {
        //select an item from the select list 
    }  
}

这篇关于获取表单中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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