Selenium 2 WebDriver - Chrome - Getting the value from a text box that is set via JavaScript
I am using Selenium 2 (latest release from Googlecode) and I have it firing up Chrome and going to a url.
When the page has loaded some javascript executes to set the value of a textbox.
I tell it to find a textbox by id which it does but it doesn't have the value within it (if I hardcode a value it finds it).
Looking at the PageSource e.g. Console.WriteLine(driver.PageSource); shows the html and the textbox is empty.
I've开发者_Python百科 tried using :
driver.FindElement(By.Id("txtBoxId") to get the element and that too doesn't fetch the value.
I've also tried ChromeWebElement cwe = new ChromeWebElement(driver, "txtBoxId"); (which complains about Stale data).
Any thoughts?
John
Finally I found the answer! This is the code that works for me
WebDriverWait wait = new WebDriverWait(_driver, new TimeSpan(0,0,60));
wait.Until(driver1 => _driver.FindElement(By.Id("ctl00_Content_txtAdminFind")));
Assert.AreEqual("Home - My Housing Account", _driver.Title);
Here is my source! http://code.google.com/p/selenium/issues/detail?id=1142
Selenium 2 does not have wait functions built in for elements in the DOM. This was the same thing as in Selenium 1.
If you have to wait for something you could do it as
public string TextInABox(By by)
{
string valueInBox = string.Empty;
for (int second = 0;; second++) {
if (second >= 60) Assert.Fail("timeout");
try
{
valueInBox = driver.FindElement(by).value;
if (string.IsNullOrEmpty(valueInBox) break;
}
catch (WebDriverException)
{}
Thread.Sleep(1000);
}
return valueInBox;
}
Or something along those lines
I use webdriver through ruby (cucumber watir-webdriver, actually), and I tend to do this:
def retry_loop(interval = 0.2, times_to_try = 4, &block)
begin
return yield
rescue
sleep(interval)
if (times_to_try -= 1) > 0
retry
end
end
yield
end
Then whenever I have content appearing due to javascript writes or whatever, i just wrap it in a retry_loop like so:
retry_loop do #account for that javascript might fill out values
assert_contain text, element
end
As you'll notice there is no performance penalty if it is already there. The reverse case (checking that something is NOT there) will always need to reach the timeout, obviously. I like the way that keeps details packed away in the method and the test code clean.
Perhaps you could use something similar in C++?
精彩评论