【发布时间】:2017-01-26 06:18:10
【问题描述】:
我正在使用带有 PageObject 模式的 PageFactory。
在其中一个网站(重型 jQuery)中,某些页面加载缓慢,尤其是第一次调用页面。我得到“元素未显示”或“NoSuchElementException”等。下拉菜单同样的事情。
所以因为当我执行 myproperty.Click() 时出现错误,我的 FindsBy 退出了 Windows 我开始调用我的“WaitElementVisible”扩展方法,取回一个元素,然后单击 这使我的属性毫无意义。我错过了显而易见的事情吗?
[FindsBy(How = How.Id, Using = "user_password")]
public IWebElement txtPassword { get; set; }
public void DoSomething()
{
txtPassword.Click // Error Element is not displayed" or "NoSuchElementException"
//So FindsBy pointless And I need todo
var myElement=myDriver.WaitElementVisible(by.Id( "user_password"),30));
myElement.Click()
}
问题:
构造函数 BasePage 是否应该实现“WaitForPageToLoad”类型 of method 寻找要显示的元素? 这能解决问题吗?
PageInitElement 是否只是初始化属性,如果未找到,则将其设置为 null 。这是否正确?
我最好忘记“[FindsBy (etc.]”并在一个方法中做所有事情吗?
是否可以编写自己的“FindsByWithWait”属性以及如何做到这一点并避免编写如下扩展方法:
示例代码:
//Ideally I would like to implement a FindsByWithWait that does below
public static IWebElement WaitElementVisible(this IWebDriver driver, By by, int timeout = 10)
{
return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until((drv) => {
try
{
var ele = drv.FindElement(by);
return ele.Displayed ? ele : null;
}
catch (StaleElementReferenceException){return null;}
catch (NotFoundException){return null;}
});
}
public abstract class BasePage
{
protected BasePage
{
WaitForPageToLoad();
}
protected void WaitForPageToLoad()
{
var wait = new WebDriverWait(myDriver, TimeSpan.FromSeconds(30));
try
{
wait.Until(p => p.Title == PageTitle);
}
catch (Exception e)
{
//log etc...
}
}
}
public class LoginPage : BasePage
{
[FindsBy(How = How.Id, Using = "user_login")]
public IWebElement txtUserName { get; set; }
[FindsBy(How = How.Id, Using = "user_password")]
public IWebElement txtPassword { get; set; }
[FindsBy(How = How.Name, Using = "commit")]
public IWebElement btnLogin { get; set; }
public void Logon(string userName, string password)
{
txtUserName.Clear();
txtUserName.SendKeys(userName);// sometimes will fail (specially site loaded for first time)
txtPassword.Clear();
txtPassword.SendKeys(password); //(fails specially site loaded for first time)
btnLogin.Click();//THIS MIGHT FAIL
}
}
I hope you can clarify and answer some of the questions above,that will help me greatly with my Selenium learning curve.
Thanks a lot
【问题讨论】:
标签: c# selenium-webdriver