c# - 下拉菜单选择在 Phantomjs 上使用 C# selenium 不起作用

标签 c# xpath selenium-webdriver phantomjs html-select

有谁知道为什么 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");

https

最佳答案

实际上您正在使用<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/

相关文章:

c# - Resharper 快速修复模板

c# - 无法在 MVC 应用程序中加载文件或程序集 'System.Reflection.TypeExtensions 错误

xml - XPath child::* 与 child::node()

xml - 如何使用xPath和XmlNamespaceManager正确查询xml片段

xml - xslt 显示前 5 个总和

java - 在 Selenium Webdriver 中,哪个在性能方面更好 Linktext 或 css?

c# - 尝试从 C# 异步调用长时间运行的存储过程时失败

c# - 在 DllImport 中使用 Unicode 字符串和用 Rust 编写的 DLL

javascript - Selenium Python 绑定(bind) : how to execute JavaScript on an element?

Python Selenium 无法通过单击表单内的按钮登录