【问题标题】:Clicking dynamic dropdown div with Selenium in Java在 Java 中使用 Selenium 单击动态下拉 div
【发布时间】:2019-07-07 21:28:33
【问题描述】:

我在从动态生成的下拉列表中指定第一个元素的 xpath 时遇到问题。我希望 Selenium 在输入一些文本后单击this webpage 下拉列表中的第一个建议。但是,我想要找到它的方式是NoSuchElementException。我的代码:

public static void printTickets() throws IOException {
    System.setProperty("webdriver.chrome.driver", CHROMEDRIVER_PATH);
    WebDriver driver = new ChromeDriver();
    driver.get("https://bilkom.pl/");

    // hide iframe
    WebElement closeFrameButton = driver.findElement(By.xpath("//div[@class='modal-body']//button[@class='close']"));
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.elementToBeClickable(closeFrameButton));
    closeFrameButton.click();

    // fill first field
    WebElement textInput = driver.findElement(By.xpath("//input[@id='fromStation']"));
    textInput.sendKeys("Warszawa");
    String firstElementXPath = "//div[@id='fromStation-cg']//div[@class='tt-dataset']//div[1]";
    WebElement firstElementDiv = driver.findElement(By.xpath(firstElementXPath)); //NoSuchElementException
    firstElementDiv.click();
}

【问题讨论】:

    标签: java selenium web-crawler selenium-chromedriver


    【解决方案1】:

    尝试使用以下 xpath 从动态列表中选择第一项。

    (//div[@id='fromStation-cg']//div[@class='tt-station tt-suggestion tt-selectable']//span)[1]
    

    检查了下面的代码,它按预期工作。

    // fill first field
        WebElement textInput = driver.findElement(By.xpath("//input[@id='fromStation']"));
        textInput.sendKeys("Warszawa");
        Thread.sleep(5000);
        String firstElementXPath = "(//div[@id='fromStation-cg']//div[@class='tt-station tt-suggestion tt-selectable']//span)[1]";
        WebElement firstElementDiv = driver.findElement(By.xpath(firstElementXPath)); //NoSuchElementException
        wait.until(ExpectedConditions.elementToBeClickable(firstElementDiv));
        System.out.println(firstElementDiv.getText());
        firstElementDiv.click();
    

    【讨论】:

      【解决方案2】:

      您的代码的问题在于您提供的 xpath。没有 < div class="tt-dataset"> 为您在任何搜索后获得的任何建议显示标签

      <div class="tt-station tt-suggestion tt-selectable">

      要选择第一个建议,您可以使用findElements

      WebElement textInput = driver.findElement(By.xpath("//input[@id='fromStation']"));
      textInput.sendKeys("Warszawa");
      List<WebElement> suggestionList = driver.findElements(By.xpath("//div[@class='tt-station tt-suggestion tt-selectable > span > i']"));
      suggestion.get(0).click();
      

      如果你想点击任何其他元素,你可以根据需要给出索引号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多