[英]Unable to get element by ID with selenium
這是我的頁面:
<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 :</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 :</b>
</td>
<td>
<input type="password" maxlength="16" size="12" id="login_pass">
<!--<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'
為什么?
根據您共享的HTML
,您已嘗試通過id
來定位元素login_name和login_pass ,該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']"))
我認為您的問題在於硒中的以下代碼: driver.FindElement(By.Id("pass_name"))
,但是在html中,您要查找的ID是: <input type="password" maxlength="16" size="12" id="login_pass">
即login_pass。
如果我錯了糾正我...
順便說一句,如果我理解正確的話,X-Path易於更改代碼:/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.