如何使用Selenium与Java处理mercurytravels.co.in的出发到达城市下拉字段
Selenium Java 实现 mercurytravels.co.in 机票城市下拉选项选择方案
前置说明
该网站的「出发城市」「到达城市」属于联想式输入下拉框,不是原生<select>标签,无法直接使用Selenium自带的Select类操作,需要按照「激活输入→输入关键词触发联想→匹配目标选项→点击选择」的逻辑实现。
实现步骤
1. 基础环境准备
首先确保你的Java项目已引入Selenium依赖,Maven配置参考如下:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.10.0</version> <!-- 可替换为最新稳定版 --> </dependency>
初始化WebDriver并打开目标页面:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.List; public class FlightCityTest { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); // 打开机票预订页面 driver.get("https://www.mercurytravels.co.in/flights"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
2. 封装城市选择通用方法
可以把城市选择逻辑封装为公共方法,减少重复代码:
/** * 选择城市方法 * @param driver WebDriver实例 * @param wait 显式等待实例 * @param inputBoxXpath 城市输入框的Xpath定位 * @param targetCityName 目标城市名称 */ public static void selectCity(WebDriver driver, WebDriverWait wait, String inputBoxXpath, String targetCityName) { // 定位并激活输入框 WebElement cityInput = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(inputBoxXpath))); cityInput.click(); cityInput.clear(); // 输入城市关键词触发联想,输入前3位即可触发匹配 cityInput.sendKeys(targetCityName.substring(0,3)); // 等待下拉联想列表加载完成 String optionXpath = "//div[contains(@class,'autocomplete-results')]//div[contains(@class,'suggestion-item')]"; wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(optionXpath))); // 遍历所有选项匹配目标城市 List<WebElement> cityOptions = driver.findElements(By.xpath(optionXpath)); for (WebElement option : cityOptions) { if (option.getText().trim().contains(targetCityName)) { option.click(); break; } } }
3. 调用方法选择出发/到达城市
// 选择出发城市:比如德里(Delhi) String fromInputXpath = "//input[@placeholder='From City']"; selectCity(driver, wait, fromInputXpath, "Delhi"); // 选择到达城市:比如孟买(Mumbai) String toInputXpath = "//input[@placeholder='To City']"; selectCity(driver, wait, toInputXpath, "Mumbai"); // 后续操作其他功能... // 退出驱动 driver.quit(); } }
注意事项
- 输入城市关键词时不需要输入完整名称,输入前3个字符即可触发联想,避免全量输入后下拉框未匹配的问题
- 必须使用显式等待等待下拉选项加载,不要用
Thread.sleep()硬编码等待,避免页面加载速度波动导致元素找不到 - 如果遇到选择后输入框值被重置的情况,可以在点击选项后加1秒的短等待,确认输入框值已回填再进行下一步操作
内容的提问来源于stack exchange,提问作者RaviS
相关产品推荐
相关产品推荐

