我正在尝试运行一个 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 value() { [本地代码] }
如果该字段是静态的,则以下内容将起作用
String script = "return document.getElementById(\"origin\").value";
String text= (String) jse.executeScript(script);
System.out.println(text);
我正在寻找一种方法来更改返回文档行以使用动态 ID,或者让脚本接受 Xpath,以便我可以包含以标记开头
最佳答案
您可以使用 XPath locator 来定位该元素像:
WebElement myInput = driver.findElement(By.xpath("//input[@name='origin']"));
完成后你可以得到它的id
attribute :
System.out.println(myInput.getAttribute("id"));
或者如果您愿意,您可以获得 value
attribute通过JavaScriptExecutor像:
System.out.println(driver.executeScript("return [0].value", myInput));
关于java - 使用 getElementById 运行 JavascriptExecutor 时如何使用动态 ID 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666161/