如何通过XPath实现点击事件填充无ID输入框值
问题
我原本通过以下代码实现点击按钮填充指定ID的输入框值:
<script> function inputfillclick() { document.getElementById('inputidx').value="KuchBhi" } </script> <input type="text" id="inputidx" name="inputidx" /> <button class="button" onclick="inputfillclick()">Fill Now</button>
但现在需要在另一页面实现相同功能,该页面的输入框无ID,其代码如下:
<input maxlength="140" step="" enterkeyhint="done" autocomplete="off" type="password" class="uni-input-input">
已知该输入框的XPath为//input[@type='password'],完整XPath为/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view/uni-view[3]/uni-view[2]/uni-view[2]/uni-input/div/input,请问能否通过XPath实现点击填充输入框值?
解答
可以通过XPath实现输入框填充,但浏览器原生JavaScript没有直接的XPath选择器API,需要借助document.evaluate方法定位目标元素,之后即可设置输入框的值。
实现方式一:使用相对XPath
相对XPath(//input[@type='password'])更灵活,只要页面中该类型的输入框唯一,就能准确匹配:
<script> function inputfillclick() { // 使用相对XPath定位元素 const xpath = "//input[@type='password']"; const inputElement = document.evaluate( xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue; if (inputElement) { inputElement.value = "KuchBhi"; } } </script> <input maxlength="140" step="" enterkeyhint="done" autocomplete="off" type="password" class="uni-input-input"> <button class="button" onclick="inputfillclick()">Fill Now</button>
实现方式二:使用完整XPath
完整XPath定位精度高,但依赖页面DOM结构,一旦页面布局变动就会失效,适合结构稳定的场景:
<script> function inputfillclick() { // 使用完整XPath定位元素 const xpath = "/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view/uni-view[3]/uni-view[2]/uni-view[2]/uni-input/div/input"; const inputElement = document.evaluate( xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue; if (inputElement) { inputElement.value = "KuchBhi"; } } </script> <input maxlength="140" step="" enterkeyhint="done" autocomplete="off" type="password" class="uni-input-input"> <button class="button" onclick="inputfillclick()">Fill Now</button>
注意事项
- 如果页面存在多个
type="password"的输入框,//input[@type='password']会匹配第一个,若要精准定位,可结合其他属性优化XPath,例如//input[@type='password' and @class='uni-input-input'] - 完整XPath对DOM结构变动极为敏感,后续页面更新可能导致定位失败,优先推荐使用相对XPath
内容的提问来源于stack exchange,提问作者user21549197
相关产品推荐
相关产品推荐

