【问题标题】:Possible to make generic function to find a particular item with Selenium WebDriver?可以使用 Selenium WebDriver 实现通用功能来查找特定项目吗?
【发布时间】:2013-09-02 13:59:07
【问题描述】:

我想创建一个通用函数来查找特定项目?

我做这个 C# 代码 (Src : Use Explicit Waits in Selenium WebDriver Correctly)

        IWebDriver driver = new FirefoxDriver();
        driver.Url = "http://somedomain/url_that_delays_loading";
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
        {
            try
            {
                return d.FindElement(By.Id("someDynamicElement"));
            }
            catch
            {
                return null;
            }
        });

我会替换 wait.Until((....); 使用通用函数。

如何定义一个通用的 By 选择器来查找特定项目?

这里是内置 Selenium2 选择器的列表:

ClassName
CssSelector
Id
LinkText
PartialLinkText
Name
TagName
XPath

例如:

IWebElement myDynamicElement = WaitForElement(????) // for exemple By.TagName = "Test"
public static IWebElement WaitForElement(**By selector**)
{
    wait.Until<IWebElement>((d) =>
    {
            try
            {
                return d.FindElement(**By selector**);
            }
            catch
            {
                return null;
            }
    });
}

【问题讨论】:

    标签: c# selenium selenium-webdriver


    【解决方案1】:
    public static IWebElement WaitForElement(IWebDriver driver, By selector)
    {    
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10);
        return wait.Until<IWebElement>(d =>
        {
                try
                {
                    return d.FindElement(selector);
                }
                catch
                {
                    return null;
                }
        });
    }
    

    这将被称为:

    WaitForElement(driver, By.Id("someDynamicElement"));
    

    你只需给它一个By 选择器的实例。然后底层的d.FindElement 调用将处理其余部分,它将处理找出它是什么“种类”的选择器。你不需要做太多。

    By 类背后的整个概念是首先使其具有通用性。您将重复工作。

    您还必须传入driver,除非您打算将其作为static 字段或driver 本身的扩展方法。

    【讨论】:

    • 感谢您的帮助 Arran。没关系。
    猜你喜欢
    • 2014-09-04
    • 2020-09-01
    • 2013-06-27
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多