java - 在 Java 中使用 Selenium 单击动态下拉 div

标签 java selenium web-crawler selenium-chromedriver

我在从动态生成的下拉列表中指定第一个元素的 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();
}

最佳答案

尝试使用下面的 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();

关于java - 在 Java 中使用 Selenium 单击动态下拉 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56926241/

相关文章:

java - Selenium webdriver 找不到我的按钮

Selenium .JavascriptException : javascript error: Failed to execute 'elementFromPoint' on 'Document' : The provided double value is non-finite

bash - 使用wget抓取网站并限制抓取链接总数

seo - 我可以在不公开的情况下允许(通过搜索引擎)索引受限内容吗?

java - 怎样才能拿到卖家的产品

java - servlet中 'main method'的作用是什么?

java - 尽管程序一次扫描一个元素,但程序仍在无限地获取输入

java.lang.ClassNotFoundException : org. apache.http.config.RegistryBuilder

ruby-on-rails - 使用 Capybara + Env.js 测试 JQuery UI 自动完成不起作用(使用 Selenium 可以)

python - 从维基百科页面获取所有链接