有谁知道为什么 Selenium 在使用 phantom
时看不到下拉菜单,而使用 firefox
则没有错误。
Driver.FindElement(By.XPath("//div[@id='searchCompositeComponent:contentForm:searchParamPane:j_id_30:sortDropdown']")).Click();
Driver.FindElement(By.XPath("//li[@data-label='data']")).Click();
Firefox
工作正常,但 phantom
在第二行给出错误,它应该从下拉列表中选择
error msg: An unhandled exception of type 'OpenQA.Selenium.ElementNotVisibleException' occurred in WebDriver.dll
也尝试过这个:
IWebElement OPT = Driver.FindElement(By.XPath("//div[@id='searchCompositeComponent:contentForm:searchParamPane:j_id_30:sortDropdown']"));
OpenQA.Selenium.Support.UI.SelectElement selectTag = new OpenQA.Selenium.Support.UI.SelectElement(OPT);
selectTag.SelectByText("Data");
最佳答案
实际上您正在使用<div>
通过提供的 id 元素,而您应该使用 <select>
元素使用 OpenQA.Selenium.Support.UI.SelectElement()
如下:
using OpenQA.Selenium.Support.UI;
//implement WebDriverWait to wait until dropdown visible
IWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10))
IWebElement dropdown = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("searchCompositeComponent:contentForm:searchParamPane:j_id_30:sortDropdown_input")));
SelectElement selectTag = new SelectElement(dropdown);
selectTag.SelectByText("Enter dropdown visible option text here");
已编辑:- 如果不幸的是选择元素不可见,您可以找到现有的选择元素并使用 IJavascriptExecutor
执行选择如下:-
IWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10))
IWebElement dropdown = wait.Until(ExpectedConditions.ElementExists(By.Id("searchCompositeComponent:contentForm:searchParamPane:j_id_30:sortDropdown_input")));
IJavascriptExecutor js = driver as IJavascriptExecutor;
js.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", dropdown, "Enter dropdown visible option text here");
关于c# - 下拉菜单选择在 Phantomjs 上使用 C# selenium 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894988/