Search code examples
javaseleniumgoogle-chromesendkeys

Problem with sending keys to a form field when there is no submit button available


I'm studying the Selenium WebDriver for a school project. I am currently creating a Maven Web Application (with jsp / servlets) that web scrapes tripadvisor data, puts it into a database and then sorts the data based on user past behavior.

My problem starts when I have to submit my keys to tripadvisor search bar. There is no submit button so I have to use org.openqa.selenium.Keys import. Here is the code I tried:

driver.findElement(By.xpath("//span[contains(@class, 'brand-trip-search-geopill-TripSearchGeoPill__icon--jEoJX')]")).click();

String keyword = request.getParameter("<parameter-inserted-by-user>");
//insert text inside search form
WebElement insert_element = driver.findElement(By.xpath("//input[@class='input-text-input-ManagedTextInput__managedInput--106PS']"));

insert_element.sendKeys(keyword+Keys.ENTER);

The problem that arises is that when I run the test, the text is inserted in the search form, but when Keys.ENTER happens the search is not committed, and it registers as if I actually wrote:

insert_element.sendKeys(Keys.ENTER);

I have been lurking around stackoverflow looking for a solution, and I tried the following alternative:

insert_element.sendKeys(keyword + "\n");

to no avail. It only registers the "Enter" command and thus offers me a search of my "Nearby" location.

I also saw I could use javascript but it looks burdensome for such a simple task as submitting a search request.

Currently I'm using Chromedriver v.2.44 and Selenium v.3.141.59

Can someone help me? Thank you in advance for your time.


Solution

  • You're hitting a timing problem. Selenium is typing really fast then pressing the enter key. Do the actions manually and you will see a slight delay between typing an getting results based on what you typed.

    I have sample code that proves the above, but am leaving this for you to figure out. The above comment and your code should be enough.

    ---Edit--- adding sample code now that the OP figured it out

    driver.findElement(By.xpath("//span[contains(@class, 'brand-trip-search-geopill-TripSearchGeoPill__icon--jEoJX')]")).click();
    
    String keyword = request.getParameter("<parameter-inserted-by-user>");
    //insert text inside search form
    WebElement insert_element = driver.findElement(By.xpath("//input[@class='input-text-input-ManagedTextInput__managedInput--106PS']"));
    
    insert_element.sendKeys(keyword);
    Thread.sleep(1000);    //  <-- Not ideal but for a permanent solution, but illustrates this is timing related.
    insert_element.sendKeys(Keys.ENTER);