Faced the situation when using Select class, selenium complains that "element not interactable".
HTML 代碼
driver.findElement(By.cssSelector("div.select")).click();
Select select = new Select(driver.findElement(By.id("phonePrefix")));
select.selectByIndex(5);
控制臺輸出
無論如何,我找到了一種通過回圈遍歷串列并按文本選擇來從下拉串列中選擇元素的方法.....
driver.findElement(By.cssSelector("div.select")).click();
WebElement drop = driver.findElement(By.cssSelector("select"));
List<WebElement> countryies = driver.findElements(By.cssSelector("ul[class='select-options'] li"));
for(WebElement i:countryies) {
System.out.println(i.getText());
if(i.getText().contains(" 93 Afghanistan")) {
i.click();
break;
}
}
但問題是為什么我不能使用 Select 類和 select.getFirstSelectedOption() 以及如何處理?謝謝
Ps 還嘗試了一些明確的等待。
driver.get("https://banking.idram.am/Account/login");
driver.findElement(By.cssSelector("div.select")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("phonePrefix")));
Select select = new Select(driver.findElement(By.id("phonePrefix")));
select.selectByIndex(5);
輸出
uj5u.com熱心網友回復:
根據您使用 HTML 代碼發布的影像,您應該以這種方式從下拉串列中選擇專案:
public class DropDownDemo {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "YOUR_PATH_TO_DRIVER_EXE_HERE");
WebDriver driver = new ChromeDriver();
driver.get("https://banking.idram.am/Account/login");
driver.manage().window().maximize();
WebElement divSelect = new WebDriverWait(driver, Duration.ofSeconds(5), Duration.ofMillis(100)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.select")));
divSelect.click();
WebElement option = new WebDriverWait(driver, Duration.ofSeconds(10), Duration.ofMillis(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[text()=' 93 Afghanistan']")));
option.click();
Thread.sleep(5000); // only to see the result
driver.close();
}
}
如果使用 Selenium 3,請洗掉Duration.ofXXX()并直接將數值傳遞給建構式。
為什么我不能使用 Select 類和 select.getFirstSelectedOption() 以及如何處理?
<select class="phonePrefix select-hidden" required="required" name="phonePrefix" id="phonePrefix">
...
</select>
正如您從發布的代碼片段中看到的那樣,Select元素正在使用select-hidden類來實作下拉選單。因此,Selenium 無法與之互動。這個應用程式使用的是Bootstrap Dropdown。此外,確定使用哪一個(即選擇與 ul/li)的最簡單方法是檢查頁面并選擇其中一個選項。當您這樣做時,它會轉到li元素而不是option元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443347.html
上一篇:如何使用物體名稱列中的值創建一個串列,該串列在“檢查”中可見,但在使用Selenium和Python的頁面源中不可見
下一篇:棄用警告:firefox_binary已被棄用,請在SeleniumPython中使用引數firefox_binary傳入服務物件
