【问题标题】:changing the value of a select box by only having the xpath仅通过 xpath 更改选择框的值
【发布时间】:2014-08-18 14:49:33
【问题描述】:

我目前正在使用 robotsium 在 android 网络视图中记录大量操作。 robotsium 中有一个已知错误,它不允许您更改选择框的值。为了在测试运行时解决这个问题,我正在创建另一个 javascript 注入来更改它。它适用于名称和 ID,但它还需要能够使用 xpath,以防名称或 ID 不可用。

目前我可以使用选择框的名称和 ID 来执行此操作:

selectBox = document.getElementById(identifyingValue);

selectBox = document.getElementByName(identifyingValue);

在此之后,我可以创建一个方法来将选择框的值更改为我想要的值。问题是有时我无法获取选择框的 ID 或名称,并且没有类似的方法可以通过 Xpath 执行此操作,即:

selectBox = document.getElementByXpath(identifyingValue);

我的代码目前如下所示:

var selectBox;
var identifyingAttribute = ('$identifyingAttribute');
var identifyingValue = ('$identifyingValue');
var selectedIndex = '$selectedIndex';
if (identifyingAttribute === 'id') {
    selectBox = document.getElementById(identifyingValue);
} else if (identifyingAttribute === 'name') {
    selectBox = document.getElementByName(identifyingValue);
} else if (identifyingAttribute === 'xpath') {
    selectBox = document.getElementByXpath(identifyingValue);   
}
selectBox.selectedIndex = selectedIndex;
if (selectBox.onchange) {
    selectBox.onchange();
}

到目前为止,您可以看到我正在尝试首先使用 id 和 name,然后将 xpath 作为最后的手段。

我可以通过 Xpath 选择一个元素,然后更改它的值或执行类似的操作。任何帮助或意见将不胜感激。

【问题讨论】:

  • 如果你不使用 jQuery,我强烈推荐它。
  • 为什么要在 HTML 文档中使用 xPath,难道不能以其他方式遍历 DOM 吗?
  • 我目前正在使用 robotsium 在 android web 视图中记录大量动作。 robotsium 中有一个已知错误,它不允许您更改选择框的值。为了在测试运行时解决这个问题,我正在创建另一个 javascript 注入来更改它。它适用于名称和 ID,但它还需要能够使用 xpath,以防名称或 ID 不可用。我正在尝试将问题隔离为一个更小更具体的问题,抱歉>

标签: javascript html xpath code-injection document.evaluate


【解决方案1】:

您可以使用 document.querySelector() 并使用 css 选择器选择属性。

文档可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

【讨论】:

    【解决方案2】:

    我使用 document.evaluate() 找到了解决问题的方法 该声明对我有用:

    selectBox = document.evaluate(identifyingValue, document, null , 9, null).singleNodeValue;
    

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2020-05-25
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多