You need to enable JavaScript to run this app. 使用Selenium在https://www.goibibo.com/hotels/ 实现城市下拉选择的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium在https://www.goibibo.com/hotels/ 实现城市下拉选择的问题咨询

Goibibo酒店页面城市选择Selenium操作修复方案

原代码失效核心原因

  • 动态ID不稳定:downshift开头的元素ID是前端动态生成的,每次页面加载都会变化,无法作为稳定定位依据
  • 无等待机制:代码执行速度远快于页面元素渲染速度,未等元素加载完成就执行查找操作,必然报错
  • 下拉菜单未触发:城市选择的下拉列表需要先在输入框输入关键词才会渲染,直接查找列表元素无法匹配
  • 反爬特征检测:网站默认会拦截Selenium自动化工具的操作请求,需要添加配置隐藏自动化特征

修复后可运行代码

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class Goibibo {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_2\\chromedriver.exe");
        // 添加Chrome配置隐藏Selenium特征,绕过反爬检测
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-blink-features=AutomationControlled");
        options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
        options.setExperimentalOption("useAutomationExtension", false);
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        // 全局隐式等待
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 打开Goibibo酒店页面
        driver.get("https://www.goibibo.com/hotels/");
        System.out.println("页面加载完成");

        // 选择印度地区,使用稳定的属性定位替代动态ID
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@value='India']"))).click();
        System.out.println("已选择印度地区");

        // 定位城市输入框,使用placeholder属性定位,稳定性更高
        By cityInput = By.xpath("//input[@placeholder='Search for City, Area, Landmark or Property']");
        wait.until(ExpectedConditions.elementToBeClickable(cityInput)).click();
        driver.findElement(cityInput).sendKeys("Mysore");
        System.out.println("已输入城市名Mysore");

        // 等待下拉选项渲染完成后选择对应城市
        By mysoreOption = By.xpath("//div[contains(text(),'Mysore')]/ancestor::li");
        wait.until(ExpectedConditions.elementToBeClickable(mysoreOption)).click();
        System.out.println("已选择城市Mysore");
    }
}

注意事项

  • 保证Chrome浏览器和chromedriver版本完全匹配,否则会出现启动失败问题
  • 如果仍然有操作拦截,可添加随机等待时间进一步模拟人工操作

内容的提问来源于stack exchange,提问作者Krishna Game Studio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 10:15:01