用于WebElements的Selenium动态选择器

用于WebElements的Selenium动态选择器,selenium,selenium-webdriver,dynamic,Selenium,Selenium Webdriver,Dynamic,我正在构建一个测试框架,我的目标是使用这个框架测试许多具有相似页面但彼此之间存在细微差异的网站 我有一个问题,我希望WebElements选择器是动态的,这意味着我希望将查找元素的方式作为参数传递给FindElement方法 我正在尝试建立这样的东西: public class WebComponent { public int ID { get; set; } public string Name { get; set; }

我正在构建一个测试框架,我的目标是使用这个框架测试许多具有相似页面但彼此之间存在细微差异的网站

我有一个问题,我希望WebElements选择器是动态的,这意味着我希望将查找元素的方式作为参数传递给FindElement方法

我正在尝试建立这样的东西:

public class WebComponent
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public IWebElement WebElement{get;set;}
            public Accessor Accessor { get; set; }
            public WebComponent()
            {
                Accessor = new Accessor();
            }

    }
    public class Accessor
    {
        OpenQA.Selenium.By By { get; set; }
        public string Value { get; set; }
    }
稍后在我的代码中,当我想拥有这个类的实例时:

WebComponent component = new WebComponent();
component.ID = 1;
component.Name = "Logout Button";
component.Description = "The button to click when user wants to logout of website";
component.Accessor.By = By.Id;
component.Accessor.Value = "logout";
component.WebElement = Browser.Driver.FindElement(//missing code);

我的问题是如何使用component.Accessor找到WebElement,任何建议或建议的编辑都将不胜感激。

By.Id
是一个方法组,您不能将其分配给type
OpenQA.Selenium.By
。任务应该是

component.Accessor.By = By.id("logout"); // or any other By and value.
然后您可以使用

component.WebElement = Browser.Driver.FindElement(component.Accessor.By);
编辑

要动态选择定位器和值,可以执行以下操作

private By chooseType(String locatorType, string value) {
    switch(locatorType) {
        case "id":
            return By.id(value);
        case "class":
            return By.className(value);
        //...
    }
}

但是这种方式不允许我使用动态访问方法,这种方法可能在{Id,Name,ClassName,etc..}@yahyahussein之间改变,为什么不呢?您可以执行
component.Accessor.By=By.Id(“注销”)
component.Accessor.By=By.className(“someClass”)下的行
Now component.Accessor.By
By.className(“someClass”)如果我想让测试人员使用combobox选择访问方法,请这样想。这种方式需要每个访问方法的if条件。@yahyahussein如果你想要动态定位器,你必须选择它们。如果要避免使用
If else
语句,可以使用
switch case
方法执行选择过程,该方法返回
By
,类似于
private By chooseType(String locatorType,String value){switch(locatorType){case“id”:return By.id(“logout”);case“class”:return By.className(“name”);}
谢谢,这很有帮助,请更新您的答案并添加此选项