【问题标题】:How to check a radio button with Selenium WebDriver?如何使用 Selenium WebDriver 检查单选按钮?
【发布时间】:2014-11-17 19:02:49
【问题描述】:

我想检查这个单选按钮,但我不知道怎么做。 我的 HTML 是:

<div class="appendContent">

    <div> id="contentContainer" class="grid_list_template">
        <div id="routeMonitorOptions"></div>
    </div>

    <input id="optionStopGrid" type="radio" name="gridSelector"/>
    <label for="optionStopGrid">Paradas</label>
</div>

【问题讨论】:

标签: java html css selenium


【解决方案1】:

This question 一定能帮到你。

您可以通过id轻松找到元素,然后您只需调用isSelected方法即可。

【讨论】:

  • 你到底尝试了什么?您能否编辑您的第一条消息,向我们展示不起作用的 Java 代码?
  • List radio = driver.findElements(By.id("optionStopGrid")); radio.get(2).getAttribute("checked");
  • 我无法选择单选按钮
  • 网页中的 id 必须是唯一的。所以,你不应该调用 findElements(复数)而是 findElement(单数),网页中必须有一个且只有一个具有此 ID 的元素。所以radio 变成:WebElement radio = driver.findElement(By.id("optionStopGrid")); 然后你只需要调用radio.isSelected();,就像上面链接中提到的那样。
【解决方案2】:

请尝试使用此代码选择单选按钮-

driver.findElement(By.cssSelector("input[id='optionStopGrid']")).click();

【讨论】:

    【解决方案3】:
    import java.util.List;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class answer {
        public static void main(String[] args) throws InterruptedException {
            WebDriver driver = new FirefoxDriver();
            driver.get("http://www.example.com/");
            //If u want to know the number of radio buttons then use List
            List<WebElement>radioButton = driver.findElements(By.tagName("example"));
            System.out.println(radioButton.size());
            //If u want to select the radio button
            driver.findElement(By.id("example")).click();
            Thread.sleep(3000);
            //If u want the Text in U R console
            for(int i=0;i<radioButton.size();i++) {
                System.out.println(radioButton.get(i).getText());
            } 
            //If u want to check whether the radio button is selected or not
            if(driver.findElement(By.id("example")).isSelected()) {
                System.out.println("True");
            } else {
                System.out.println("False");
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      在选择元素之前使用 time.sleep() 或 implicit() 或显式 () 等待 then driver.find_element_by_id("profile_id_2559380").click()

      【讨论】:

      • 建议:添加代码示例以突出代码并使其更具可读性。
      【解决方案5】:

      我知道我迟到了,但我想加两分钱。 有时,简单的.click() 不起作用,因为您选择的是input 标签,而实际上它是我们作为人类单击的附加span 标签。 在您拥有input 标签的情况下,您可以做的是转到父级,然后找到要单击的兄弟span,如下所示:

      optionInput.parent().$("span").click();
      

      【讨论】:

        猜你喜欢
        • 2014-06-15
        • 2014-07-11
        • 2020-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-08
        • 2019-12-14
        相关资源
        最近更新 更多