代码之家  ›  专栏  ›  技术社区  ›  ocp1000

无法使用selenium按ID获取元素

  •  0
  • ocp1000  · 技术社区  · 7 年前

    这是我的页面:

    <table class="formarea" border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="form_label_40">
                <script>prints(ot_login_username);</script>Username&nbsp;:</td>
            <!--<td></td>-->
            <td>
                <input type="text" maxlength="16" size="12" id="login_name">
                </td>
            </tr>
            <tr>
                <td class="form_label_40">
                    <b>
                        <script>prints(ot_login_password);</script>Password&nbsp;:</b>
                </td>
                <td>
                    <input type="password" maxlength="16" size="12" id="login_pass">&nbsp;&nbsp;
                        <!--<script>prints("<input type='button' value='"+ot_login_login+"' onclick='checkForm();'>");</script>-->
    
                    </td>
                </tr>
    

    我正在努力获取元素 login_name login_pass 使用硒:

    driver.FindElement(By.Id("login_name"))
    driver.FindElement(By.Id("pass_name"))
    

    但我发现了错误 OpenQA.Selenium.NoSuchElementException: 'no such element' 为什么?

    2 回复  |  直到 7 年前
        1
  •  1
  •   undetected Selenium    7 年前

    根据 HTML 您已共享您已尝试定位元素 login\u名称 登录\u密码 通过 id 这不是唯一地标识元素。要识别唯一的,您必须采用 Locator Strategy 具体如下:

    //login_name field
    driver.FindElement(By.XPath("//table[@class='formarea']//input[@id='login_name']"))
    //login_pass field
    driver.FindElement(By.XPath("//table[@class='formarea']//input[@id='login_pass']"))
    
        2
  •  0
  •   yosefc    7 年前

    我认为您的问题在于selenium中的以下代码: driver.FindElement(By.Id("pass_name")) ,但在html中,您要查找的id是: <input type="password" maxlength="16" size="12" id="login_pass"> i、 e,login\u pass。

    如果我错了,请纠正我。。。

    顺便说一句,如果我理解正确,X-Path容易受到代码更改的影响:/