Selenium - 在javascript加载元素后DOM没有刷新

时间:2013-05-08 14:52:27

标签: c# selenium

我正在寻找以下元素:

<input id="login_input" value="" class="input_long " type="text" name="login" tabindex="1">

在初始页面完全加载后,此元素由javascript加载。现在这是我获取此元素的代码:

IWebDriver _drv = new ChromeDriver();
_drv.Navigate().GoToUrl("http://mysite.com");
System.Threading.Thread.Sleep(2000);
do
{
    try
    {
        _drv.FindElement(By.Id("login_input")).SendKeys("555567756756");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
} while (true);

它给我的错误是A first chance exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll,显然这个元素在网站上可见。

我该怎么做才能获得这个元素?

更新:稍微更改了我的代码:

IWebDriver _drv = new ChromeDriver();
_drv.Url = "http://mysite.com";
//_drv.Navigate().GoToUrl("http://mysite.com");
do
{
    try
    {
        WaitUntilPresent(By.Id("login_input")).SendKeys("555567756756");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
} while (true);

IWebElement WaitUntilPresent(By element)
{
    return new WebDriverWait(_drv, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(element));
}

上面给出了超时异常,这是因为在页面上的javascript加载了元素后,_drv.PageSource没有被更新。

1 个答案:

答案 0 :(得分:1)

尝试使用显式等待。 -
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#explicit-waits

您收到该错误是因为FindElement()错误,如果它不存在则错误。你说它就在那里,但这段代码可能会在它可见之前执行。

您的代码看起来像

IWebDriver _drv = new ChromeDriver();
_drv.Get("http://mysite.com"); // don't use Navigate().GotoUrl().
// Don't use waits.. WebDriver has what's called "implicit waits" which prevent you from having to use Sleep().  That is why you don't see `selenium.waitForPageToLoad()` anymore.
WebElement field = waitUntilPresent(_drv.FindElement(By.Id("login_input")));
field.SendKeys("555567756756");


...
WebElement waitUntilPresent(WebElement element) {
    return new WebDriverWait(_drv, 10)) // might have to do some casting here
    .until(ExpectedConditions.PresenceOfElementLocated(element));
}