Nimal krishna
Nimal krishna

Reputation: 51

How to click on element using xpath in selenium webdriver?(Usually it works for me , but dont works for this specific url)

I am trying to click on an input field in the Website-link using xpath
usually it works for me for all urls.. but for this specific url whatever I try I cant click on the input field using selenium webdriver.

Webdriver loads the page but won't click on the element.
This is what I have tried so far: (it is a java project for test automation using Selenium webdriver)

System.setProperty("webdriver.gecko.driver", "C:\\Users\\nimal\\eclipse-workspace\\webdriver\\chromedriver.exe") ;
      WebDriver driver = new ChromeDriver();
       driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); 
       driver.get("https://www.kayak.com/flights");

       WebElement searchfield1 =  driver.findElement(By.xpath("//*[@id='c5NwV-origin-airport-display']")); 
       searchfield1.click();
       WebElement searchfield2 =  driver.findElement(By.xpath("//*[@id='c5NwV-origin-airport']")); 
       searchfield2.sendKeys("Toronto");

I tried to first click on the div element using xpath, as then only I get the input field.
Then tried to send "Toronto" to the input field using xpath.

Any help or suggestions are most welcome.

Upvotes: 1

Views: 859

Answers (1)

Subburaj
Subburaj

Reputation: 2334

Here, the id is getting changed dynamically.So, you need to find the element using other unqiue reference and you need to change your Xpath locator for the searchfield1 as //div[@class='search-form-inner']//div[@data-placeholder='From?']

searchfield2 element can be find using the name attribute. you need to perform clear action before sending the key.Since,some of the data is pre populated in the origin field

As a best practice add some wait after loading the URL for the page load completion.

Working Code:

driver.get("https://www.kayak.com/flights");

WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Flights"));

WebElement searchfield1 =  driver.findElement(By.xpath("//div[@class='search-form-inner']//div[@data-placeholder='From?']"));
searchfield1.click();

wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("origin")));

WebElement searchfield2 =  driver.findElement(By.name("origin"));
searchfield2.clear();
searchfield2.sendKeys("Toronto");

Upvotes: 3

Related Questions