0

I am attempting to run a selenium script which will return the text displayed on the screen after a user input into a dynamic search field.

I am able to enter the text and see the results on screen but my Javascript to output the text does not work as the ID field I am using is dynamic.

I am trying to get the text to display in the Browser Console so I can use that in my Javascript. If I try by ID but use the dynamically assigned ID then I get the appropriate return, however, the next time the page refreshes that ID will no longer be valid.

The HTML is as follows:

<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">

If I try to use getElementsByClassName instead then on running that in the browser console I don't get what I'm looking for;

"f values() { [native code] }

If the field was static then the following would work

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

I'm looking for a way of either changing the return document line to use a dynamic id or showever make the script accept the Xpath so I can include a starts with tag

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Steven K
  • 13
  • 3

2 Answers2

1

I think you can find it by name. Please try this:

String script = "return document.getElementsByName(\"origin\").value";
QA123
  • 30
  • 5
1

You can locate the element using XPath locator like:

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

once done you can get its id attribute:

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

or if you want you can obtain the value attribute via JavaScriptExecutor like:

 System.out.println(driver.executeScript("return [0].value", myInput));
Dmitri T
  • 159,985
  • 5
  • 83
  • 133
  • Perfect thanks! I spent so long trying to work out how to make it so that the getElementById tag used only part of the ID tag in a sort of xpath starts-with manner and never thought to work out what the ID was before I got to that part and just add it in. – Steven K Jun 19 '19 at 12:24
  • @StevenK Instead of xpath you can use `By.name("origin")` as well. – Saurabh Gaur Jun 19 '19 at 12:54
  • There's no point in getting the ID once you have the element. If you really need to click, etc. using JS, you can just pass in the element and click it. – JeffC Jun 19 '19 at 13:48