我在select2元素上遇到错误" System.InvalidOperationException:java.lang.String无法强制转换为org.openqa.selenium.WebElement "当试图从中选择价值时。奇怪的是,有时测试通过,我在使用相同代码的其他select2元素上没有问题。这可能是什么问题?
Driver.FindElement(By.XPath("//*[@id='s2id_State']/a/span[2]/b")).Click();
Driver.FindElement(By.CssSelector("#select2-drop input.select2-input")).SendKeys("1000");
wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.XPath("//table/tbody/tr/td[1]/div[text()='1000']"), "1000")); //Error line
Driver.FindElement(By.XPath("//table/tbody/tr/td[1]/div[text()='1000']")).Click();
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByXPath(String xpath)
at OpenQA.Selenium.By.<>c__DisplayClasse.<XPath>b__c(ISearchContext context)
at OpenQA.Selenium.By.FindElement(ISearchContext context)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
at OpenQA.Selenium.Support.UI.ExpectedConditions.<>c__DisplayClass26.<TextToBePresentInElementLocated>b__25(IWebDriver driver)
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at Automated.Test.Select2Test() in C:\....:line 86
远程Webdriver:
case "remote":
var huburl = new Uri(ConfigurationManager.AppSettings["SeleniumHubAddress"]);
DesiredCapabilities capabilities;
switch (ConfigurationManager.AppSettings["WebDriverBrowserCapabilities"].ToLower())
{
case "firefox":
capabilities = DesiredCapabilities.Firefox();
break;
case "ie":
capabilities = DesiredCapabilities.InternetExplorer();
break;
case "chrome":
capabilities = DesiredCapabilities.Chrome();
break;
default:
throw new NotImplementedException(string.Format("WebDriverBrowserCapabilities of \"{0}\" is not implemented for {1} mode", ConfigurationManager.AppSettings["WebDriverBrowserCapabilities"].ToLower(), ConfigurationManager.AppSettings["WebDriverMode"].ToLower()));
}
capabilities.IsJavaScriptEnabled = true;
driver = new AdvancedRemoteWebDriver(huburl, capabilities);
break;
default:
throw new NotImplementedException();
答案 0 :(得分:2)
如果您使用的文字用户如下xpath:
//table/tbody/tr/td[1]/div[text()='1000']"
答案 1 :(得分:1)
您可以尝试使用ExpectedConditions
进行显式等待WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.XPath("//table/tbody/tr/td[1]/div"), "1000")).Click();
在点击之前,元素将等待最多10秒,以使文本为“1000”。您也可以使用
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//table/tbody/tr/td[1]/div[.='1000']"))).Click();
答案 2 :(得分:0)
Selenium for C#为WebDriverWait.Until()
方法提供了几个预先构造的参数。因此,您无需致电FindElement()
。
也许你可以试试像
这样的东西wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//table/tbody/tr/td[1]/div[.='1000']")));
如果这也不起作用,那么你的XPath字符串可能不正确(我只是将你的问题复制到我的答案中)。