Get all Elements in a Form

后端 未结 4 1317
渐次进展
渐次进展 2021-02-02 14:56

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

4条回答
  •  野的像风
    2021-02-02 15:22

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

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

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

    or directly using:

    List 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 
        }  
    }
    

提交回复
热议问题