2017-08-01 142 views
-2

這是源代碼:如何使用Selenium從下拉列表中選擇一個值?

<select name="backgroundcolor" onchange="backgroundColor();"> 
    <option value="200">Red</option> 
    ....  
</select> 

我嘗試下面的代碼,以選擇「紅色」選項,但沒有奏效。

Select dropDown = new Select(driver.findElement(By.name("backgroundcolor"))); 
dropDown.selectByValue("200"); 

我越來越NoSuchElementException異常

無法找到元素// * [名稱= '的backgroundColor']

+0

你使用[webdriver.io](http://webdriver.io)? – Cristy

+0

不,這是一個FirefoxDriver。 – gingerdd

+1

[Webdriver - 無法找到元素(Java)]的可能重複(https://stackoverflow.com/questions/39373814/webdriver-unable-to-locate-element-java) –

回答

0

試試這個

Select select = new Select(driver.findElement(By.name("backgroundcolor"))); 
select.deselectAll(); 
select.selectByVisibleText("Red"); 

也許By.name是問題,我習慣使用類似於:

By.xpath("//path_to_drop_down")) 
0

試試這個,你需要下面的代碼轉換爲語言使用的是

from selenium.webdriver.support.select import Select as WebDriverSelect 
element = WebDriverSelect(driver.find_element_by_name('backgroundcolor')) 
element.select_by_value('200') 
0

你注意,這是可能的時序問題。如果是這樣,您需要等到元素出現在頁面上。試試這個:

By locator = By.name("backgroundcolor"); 
WebDriverWait wait = new WebDriverWait(driver, 30); 
wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 
Select dropDown = new Select(driver.findElement(locator)); 
dropDown.selectByValue("200"); 
0

我「找不到元素* [名稱=‘的backgroundColor’]」當我首次嘗試以達到其包含dropdown.It是一個時間問題通過iframe的error.I解決了這個問題方式。

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(theindexofframe)); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("backgroundcolor"))); 

你應該等待iframe來後,你應該等待「的backgroundColor」元素被加載到加載also.After,你可以選擇從下拉菜單中這樣的值:

Select dropDown = new Select(driver.findElement(By.name("backgroundcolor"))); 
dropDown.selectByValue("200"); 
相關問題