有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java下拉列表不适用于此站点的selenium

嗨,我试着使用下面的代码使用foodpanda网站的下拉列表并选择城市名称,但它对我不起作用

public static void main(String args[]) throws InterruptedException{
        System.setProperty("webdriver.chrome.driver","C:/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.foodpanda.in/restaurants/city/pune?gclid=CIbFi5iEvdMCFdeFaAodujsK5w");
        Thread.sleep(5000);


        WebElement drp =driver.findElement(By.id("cityId"));
        Select drp2 = new Select(drp);
        drp2.selectByVisibleText("Bangalore");

它给出了错误- 线程“main”组织中出现异常。openqa。硒。ElementNotVisibleException:元素不可见:元素当前不可见,不能进行操作


共 (2) 个答案

  1. # 1 楼答案

    <select>元素具有CSS display: none;。它只是一个占位符。 我认为该网站使用了一些花哨的<span>来获得下拉列表的精彩外观。你能查一下吗

  2. # 2 楼答案

    所以我试图弄清楚下拉菜单是如何工作的;这是我发现的。select只是一个占位符,它在网页上没有角色。单击input框(见下文)时,使用javascript调用填充下拉列表

    enter image description here

    input框内单击后,会添加一些DOM元素,其中包含带有城市名称的<p>标记,单击该标记时,将选择要选择的目标城市

    根据我的观察,当点击输入元素时,类名为spantt-suggestions是可见的。这个span中有一个div,其中有所有的p元素。你应该点击相应的p元素,该元素包含你想要的城市名称的文本

    下面是一个工作代码:

    WebDriverWait wait = new WebDriverWait(driver, 30);
    driver.findElement(
        By.xpath("//input[@class='form-control twitter-typeahead tt-input']")
    ).click(); // this will click inside the input element
    WebElement drp = (WebElement) wait.until(ExpectedConditions.presenceOfElementLocated(
                     By.xpath("//span[@class='tt-suggestions']"))); // this is the span element which gets populated
    System.out.println(drp.getAttribute("innerHTML")); // just in case you want to see the above span's HTML code
    drp.findElement(By.xpath("//div/p[text()[contains(.,'Bangalore')]]")).click(); // This will select Bangalore from the Dropdown