0

I'm trying to select Chicago, IL from the Search City or Zip Code search box on https://weather.com/

Here's the code I've tried

driver.get("https://weather.com/");
driver.manage().window().maximize();
WebElement from = driver.findElement(By.id("LocationSearch_input"));
from.sendKeys("Chicago, IL");
Thread.sleep(500);
from.sendKeys(Keys.ARROW_DOWN);
from.sendKeys(Keys.ENTER);`

Any Help is appreciated. Thank you.

zjboris
  • 25
  • 2

2 Answers2

0

Actually it's better to wait for autosuggestions to be present (they are loaded with delay) and to click on element that contains your text input.

Like:

driver.get("https://weather.com/");
driver.manage().window().maximize();

WebDriverWait wdwait = new WebDriverWait(driver, 10);
By inputLocator = new By.ById("LocationSearch_input");
wdwait.until(ExpectedConditions.elementToBeClickable(inputLocator));
WebElement from = driver.findElement(inputLocator);
from.click();
String city = "Chicago, IL";
from.sendKeys(city);
String cityLocator = String.format("//*[@data-testid='ctaButton' and contains(.,'%s')]", city);
wdwait.until(ExpectedConditions.presenceOfElementLocated(new By.ByXPath(cityLocator)));
driver.findElement(new By.ByXPath(cityLocator)).click();

Try this code, it works for me.

Yaroslavm
  • 1,762
  • 2
  • 7
  • 15
  • Thank you this worked. I did need to update the first line of code because I saw The constructor WebDriverWait(WebDriver, int) is undefined error to the following WebDriverWait wdwait = new WebDriverWait(driver, Duration.ofSeconds(10)); – zjboris Jul 31 '23 at 18:52
  • @zjboris I am using old version of Selenium, in `4.xx` signature of `WebDriverWait` changed, so, yep, you should use `Duration.ofSeconds`. If it works, can you mark this answer as correct, plz? :) – Yaroslavm Jul 31 '23 at 19:02
0

In the website National and Local Weather Radar, Daily Forecast, Hurricane and information from The Weather Channel and weather.com the option with text Chicago, IL, United States is a dynamic element so to click on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • Code block:

    driver.get("https://weather.com/");
    new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#LocationSearch_input"))).sendKeys("Chicago, IL");
    new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='LocationSearch_listbox']//button[contains(., 'Chicago, IL, United States')]"))).click();
    
  • Browser snapshot:

Chicago

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352