如何使用Selenium从下拉列表中选择一个值?
问题描述:
这是源代码:如何使用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']
答
试试这个
Select select = new Select(driver.findElement(By.name("backgroundcolor")));
select.deselectAll();
select.selectByVisibleText("Red");
也许By.name是问题,我习惯使用类似于:
By.xpath("//path_to_drop_down"))
答
试试这个,你需要下面的代码转换为语言使用的是
from selenium.webdriver.support.select import Select as WebDriverSelect
element = WebDriverSelect(driver.find_element_by_name('backgroundcolor'))
element.select_by_value('200')
答
你注意,这是可能的时序问题。如果是这样,您需要等到元素出现在页面上。试试这个:
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");
答
我“找不到元素* [名称=‘的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");
你使用[webdriver.io](http://webdriver.io)? – Cristy
不,这是一个FirefoxDriver。 – gingerdd
[Webdriver - 无法找到元素(Java)]的可能重复(https://stackoverflow.com/questions/39373814/webdriver-unable-to-locate-element-java) –