【问题标题】:How can I use an ID field which is dynamic when running JavascriptExecutor with getElementById如何在使用 getElementById 运行 JavascriptExecutor 时使用动态的 ID 字段
【发布时间】:2019-06-19 11:02:37
【问题描述】:

我正在尝试运行一个 selenium 脚本,该脚本将在用户输入动态搜索字段后返回屏幕上显示的文本。

我可以输入文本并在屏幕上查看结果,但我的 Javascript 无法输出文本,因为我使用的 ID 字段是动态的。

我正在尝试让文本显示在浏览器控制台中,以便在我的 Javascript 中使用它。如果我按 ID 尝试但使用动态分配的 ID,那么我会得到适当的返回,但是,下次刷新页面时,该 ID 将不再有效。

HTML如下:

<input 
    type="text" 
    id="origin-29890" 
    name="origin" 
    class="ej-input origin ui-autocomplete-input" 
    required="" 
    aria-label="From Airport" 
    data-routesearch-placeholder="e.g. London Gatwick" 
    aria-describedby="route-search-origin-description" 
    aria-autocomplete="list" 
    aria-expanded="false" 
    autocomplete="off" 
    aria-owns="ui-id-1" 
    placeholder="e.g. London Gatwick" 
    aria-activedescendant="selected-autocomplete-item">

如果我尝试使用 getElementsByClassName 而不是在浏览器控制台中运行它,我不会得到我要查找的内容;

"f values() { [native code] }

如果该字段是静态的,那么以下将起作用

String script = "return document.getElementById(\"origin\").value";
String text= (String) jse.executeScript(script);
System.out.println(text);

我正在寻找一种方法,要么将返回文档行更改为使用动态 id,要么让脚本接受 Xpath,以便我可以包含一个以标签开头的方法

【问题讨论】:

  • 如何将 id 分配给全局变量并在 getElementById() 中使用它?
  • 你能分享你的 HTML 吗?
  • 按要求添加了 HTML
  • 是否要尝试将文本发送到From Airport 字段,然后从同一字段中提取相同的文本?你的具体用例是什么?

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

您可以使用XPath locator 来定位元素,例如:

WebElement myInput = driver.findElement(By.xpath("//input[@name='origin']"));

完成后,您可以得到它的id attribute:

System.out.println(myInput.getAttribute("id"));

或者,如果您愿意,您可以通过JavaScriptExecutor 获得value attribute,例如:

 System.out.println(driver.executeScript("return [0].value", myInput));

【讨论】:

  • 非常感谢!我花了很长时间试图弄清楚如何制作它,以便 getElementById 标记以一种 xpath 开头的方式仅使用 ID 标记的一部分,并且在我到达那部分之前从未想过要弄清楚 ID 是什么只需添加它。
  • @StevenK 您也可以使用 By.name("origin") 代替 xpath。
  • 拥有元素后,获取 ID 毫无意义。如果确实需要使用JS点击等,直接传入元素点击即可。
【解决方案2】:

我想你可以通过名字找到它。请试试这个:

String script = "return document.getElementsByName(\"origin\").value";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2017-08-18
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    相关资源
    最近更新 更多