OpenQA.Selenium.ElementNotVisibleException:元素当前不可见,因此可能无法与之交互

时间:2014-08-14 07:09:10

标签: c# selenium-webdriver

我正在尝试使用if..else调用方法。下面是我试图从下拉列表中选择字符串国家的C#代码。我希望方法WePay()被调用。但是让元素不可见异常。

String country = "United States - US Dollars ($)";

new SelectElement(wd.FindElement(By.Id("CountrySelector"))).SelectByText(country);

if (country != "United States - US Dollars ($)")
{
    PayPal();
}
else
{
    WePay();
}

以下是方法WePay()

的C#代码
public void WePay()
{
    wd.FindElement(By.XPath("//button[@onclick='ValidateSubmit()']")).Click();
    wd.FindElement(By.Id("addAmount")).Click();
    wd.FindElement(By.Id("addAmount")).SendKeys("10");
    wd.FindElement(By.XPath("//button[@onclick='PayNow();']")).Click();
    wd.FindElement(By.Id("new-cc")).Click();
    new SelectElement(wd.FindElement(By.Id("Card_TransactionTypeId"))).SelectByText("Visa");
    wd.FindElement(By.Id("Number")).SendKeys("4003830171874018");
    wd.FindElement(By.Id("CVV")).SendKeys("527");
    new SelectElement(wd.FindElement(By.Id("Card_ExpirationMonth"))).SelectByText("10");
    new SelectElement(wd.FindElement(By.Id("Card_ExpirationYear"))).SelectByText("2020");
    wd.FindElement(By.Id("saved-address")).Click();
    new SelectElement(wd.FindElement(By.Id("AddressSelector"))).SelectByValue("69918");
    wd.FindElement(By.Id("submitButton")).Click();

}

2 个答案:

答案 0 :(得分:0)

如果您告诉我们您收到的错误消息,以及您在错误消息中的确切位置,我们可以为您提供更好的帮助。

我只是在Java中重构您的代码:

String country = "United States - US Dollars ($)";
Select select=new Select(wd.FindElement(By.Id("CountrySelector"))
select.selectByVisibleText(country);  //Here selects the country
//Now to cross check, get the value which is selected by below statement.
String returnSelectedCountry=select.getFirstSelectedOption(); //This will actually fetch the value from the listbox
if(!country.equals(returnSelectedCountry)) //Comparing the string var with actual val selected
  PayPal();
else
  WePay();

答案 1 :(得分:0)

根据我的经验,我有两个解决方案:

  1. 在与元素交互时使用等待,尤其是在浏览不同页面时。大多数时候,JS在加载之前都试图与HTML元素进行交互。在这种情况下,我使用自己的方法扩展了Selenium Wait,在给定的时间内检查/等待元素条件。

  2. 使用Chrome / IE驱动程序时请记住,某些元素甚至无法加载和存在都无法正常处理。在我的情况下,完成返回按钮位于屏幕可见部分的底部,我不得不使用向下滚动选项为了与他们互动。

  3. 希望它有所帮助。

相关问题