[英]How I can select an element from a dropdown list?
問題:我嘗試 select 下拉列表中的一個元素
我有一個包含以下 HTML 代碼的下拉列表:
<span class="wpcf7-form-control-wrap localitate">
<select name="localitate" class="wpcf7-form-control wpcf7-select form-control" id="cf_location_trigger" aria-invalid="false">
<option value="">Locatie</option>
<option value="Bucuresti CARAMFIL">Bucuresti CARAMFIL</option>
<option value="Bucuresti THE LIGHT">Bucuresti THE LIGHT</option>
<option value="Cluj-Napoca">Cluj-Napoca</option>
<option value="Iasi">Iasi</option></select></span>
我嘗試使用以下 Java 代碼對元素進行 select 但沒有奏效:
location.click();
WebDriverWait waits = new WebDriverWait(driver, 20);
waits.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"cf_location_trigger\"]"))).click();
Select dropdownLocation = new Select(driver.findElement(By.xpath("//*[@id=\"cf_location_trigger\"]")));
dropdownLocation.selectByIndex(3);
我怎么能 select 元素,我試圖增加等待的時間,我也嘗試了Thread.sleep ()
但它仍然無法識別列表或dropdownLocation.selectByText("Bucuresti CARAMFI");
dropdownLocation.selectByText("Bucuresti");
我沒有看到任何選項文本為Bucuresti
嘗試替換為:
Bucuresti CARAMFIL
添加更多內容:
waits.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"cf_location_trigger\"]"))).click();
您無需click
Select WebElement
,因為它會由您使用的Select
class 處理。
您應該使用id ,不要將 ID 與 XPATH 一起使用。 直到有必要。
像這樣的東西:
Select dropdownLocation = new Select(driver.findElement(By.id("cf_location_trigger")));
更新1:
代碼順序:
Select dropdownLocation = new Select(driver.findElement(By.id("cf_location_trigger")));
dropdownLocation.selectByText("Bucuresti CARAMFI");
更新2:
WebDriverWait wait = new WebDriverWait(driver, 20);
Actions action = new Actions(driver);
action.moveToElement(wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("cf_location_trigger")))).build().perform();
Select select = new Select(wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("cf_location_trigger"))));
select.selectByVisibleText("Bucuresti CARAMFI");
看看這是否有效
Select select = new Select(driver.findElement(By.xpath(".//select[@name='localitate']")));
select.selectByVisibleText("Bucuresti CARAMFIL");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.