2017-05-12 13 views
1

我想從下拉菜單中選擇一個項目。但在編譯時,無法找到元素。使用XPath選擇下拉選項 - Visual Studio

<select name="ctl00$cphmain$ddlWorkstation" onchange="javascript:setTimeout('__doPostBack(\'ctl00$cphmain$ddlWorkstation\',\'\')', 0)" id="ctl00_cphmain_ddlWorkstation" class="dropdown_s" style="width:180px;"> 
<option value="Select" title="Select">Select</option> 
<option selected="selected" value="2" title="Hospital A">Hospital A</option> 
</select> 

我寫的代碼是:

IWebElement facilityName = driver.FindElement(By.XPath("//select[@name='ctl00$cphmain$ddlWorkstation']")); 
SelectElement select = new SelectElement(facilityName); 
select.SelectByText("Hospital A"); 

我面對的錯誤:

Test method ChromeProject.Login.Chrome_Login threw exception: 
OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@name='ctl00$cphmain$ddlWorkstation']"} 
    (Session info: chrome=58.0.3029.110) 
    (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64) 

回答

0

這似乎是你要處理動態的元素。您可能需要等待一段時間,直到select目前在DOM

var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); 
IWebElement facilityName = wait.Until(ExpectedConditions.ElementIsClickable(By.XPath("//select[@name='ctl00$cphmain$ddlWorkstation']"))); 
SelectElement select = new SelectElement(facilityName); 
select.SelectByText("Hospital A"); 
+0

它的工作對加入「等待」。萬分感謝! –