【问题标题】:Get value from javascript using "getElementById" to java [duplicate]使用“getElementById”从javascript获取价值到java [重复]
【发布时间】:2020-01-27 17:19:29
【问题描述】:

我在 java 中有一个 selenium 测试,它使用函数 findElement(By.xpath("actual xpath")).getAttribute("actual attribute") 在 DEV 环境中运行良好,它为我提供了一个输入值。我尝试在 PROD 环境中运行相同的测试,但找不到此属性。由于某种原因,此输入的值在 xpath 中的任何位置都不可见。我知道输入的 id,所以我在浏览器的控制台中编写了一个简单的 javascript 函数 document.getElementById("actual id").value,它返回了我需要的正确值,因此遗憾的是,该信息对 java 隐藏,但不是从 javascript 隐藏。有没有办法,如何在我的 java 代码中使用这个 javascript 函数?

这是我尝试过的:

String id = driver.findElement(By.xpath("//label[text()='First Name(s)']")).getAttribute("for");
JavascriptExecutor js = (JavascriptExecutor) driver;
String method = "\"return document.getElementById('" + id + "').value;\"";
Object name = js.executeScript(method);

如您所料,它没有用。对象name 只返回null。 我确定id 是正确的,通过调试验证了它,所以我不得不在其他地方出错。

开发环境:

<input _ngcontent-eqp-c44 class="input-element ng-untouched ng-pristine ng-valid" ng-reflect-model="John" id="input_id_3301863451932101" type="text">

我需要来自ng-reflect-model 的值“John”,这在这种环境下非常容易,但是

生产环境:

<input _ngcontent-xjq-c2 class="input-element ng-untouched ng-pristine ng-valid" id="input_id_6695429395219272" type="text">

There you can see more of the HTML

没有什么我可以用 java...

【问题讨论】:

  • 您是否尝试过使用 WebDriver 通过 id 查找此元素? driver.findElementById("yourId");?
  • @Vault23 我尝试driver.findElement(By.id(id)); 将其作为WebElement 获取,但它不包含我正在寻找的值,我什至尝试在最后添加.getText(),但我应该知道它不会起作用,因为 没有innerHTML。我是多么愚蠢……
  • 尝试 ele.getAttribute('value')。它可能会起作用。
  • 在浏览器开发工具的 js-console 中运行时 js 工作正常吗?
  • 使用 PROD 环境中的更多外部 HTML 更新问题

标签: javascript java selenium e2e-testing


【解决方案1】:

我建议在脚本中尝试类似elem.getAttribute('ng-reflect-model')

【讨论】:

    【解决方案2】:

    终于找到答案了!谢谢大家的合作!! 我只需要用String name = js.executeScript(method).toString(); 更改代码Object name = js.executeScript(method); 的最后一部分,所以如果有人和我有同样的问题,您可以使用javascript 和输入ID 获取java 中输入的值,如下所示:

    String id = driver.findElement(By.xpath("//label[text()='First Name(s)']")).getAttribute("for");
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String method = "return document.getElementById('" + id + "').value;";
    String name = js.executeScript(method).toString();
    

    【讨论】:

    • 您不应该将js.executeScript(method).toString() 转换为String,因为toString() 返回一个String 对象
    • @AlexeyR。好点,我会编辑答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2012-09-19
    相关资源
    最近更新 更多