[英]Clicking dynamic dropdown div with Selenium in Java
我在從動態生成的下拉列表中指定第一個元素的xpath時遇到問題。 我希望Selenium在輸入一些文本后,從該網頁的下拉列表中單擊第一個建議。 但是,我要查找它的方式導致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();
代碼的問題是您提供的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();
如果要單擊任何其他元素,則可以根據需要提供索引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.