如何使用 Selenium 从动态下拉列表中选择一个选项?

新手上路,请多包涵

我正在尝试单击下拉值以从 Make my trip http://www.makemytrip.com/ 的字段中选择城市。但是获取 Stale 元素引用异常。 ID 在页面加载时发生变化。尝试了以下代码:

 driver.findElement(By.xpath(".//*[@id='hp-widget__sfrom']")).clear();
driver.findElement(By.xpath(".//*[@id='ui-id-1']"));
driver.findElement(By.xpath(".//*[@id='hp-widget__sfrom']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeSelected(driver.findElement(By.xpath(".//*[@class='ui-menu-item'][2]"))));

原文由 user2377826 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 458
2 个回答

要单击下拉值(例如 孟买),您可以使用以下解决方案:

  • 代码块:
   driver.get("https://www.makemytrip.com/")
  new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='input_fromto checkSpecialCharacters ui-autocomplete-input' and @id='hp-widget__sfrom']"))).click();
  List<WebElement> myList = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[@class='ui-menu-item'][starts-with(@id,'ui-id-')]//span[@class='autoCompleteItem__label']")));
  for (WebElement element:myList)
      if(element.getText().contains("Mumbai"));
          element.click();

  • 浏览器快照:

来自孟买

原文由 undetected Selenium 发布,翻译遵循 CC BY-SA 4.0 许可协议

下面的代码对我来说工作正常,它也被参数化,它适用于任何输入值而不改变 xpath。在这个例子中,我以孟买作为测试数据。

     driver.get("https://www.makemytrip.com/");
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.findElement(By.xpath("//input[contains(@id,'hp-widget__sfrom')]")).clear();
    driver.findElement(By.xpath("//input[contains(@id,'hp-widget__sfrom')]")).click();
    driver.findElement(By.xpath("//input[contains(@id,'hp-widget__sfrom')]")).sendKeys("Mumbai");
    Thread.sleep(2000);
    WebDriverWait wait = new WebDriverWait(driver, 30);
    By option = By.xpath("//div[@class='autoCompleteItem']/p/span[contains(text(),'Mumbai')]");
    wait.until(ExpectedConditions.elementToBeClickable(option));
    driver.findElement(option).click();

原文由 Bhargav Marpu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题