首页 > 解决方案 > 按类名选择和按css选择之间的区别?C#

问题描述

下面这段代码有什么区别:

IWebElement oldElement = driver.FindElement(By.CssSelector(".p-client_container"));
IWebElement oldElement = driver.FindElement(By.ClassName("p-client_container"));

哪个更快?另外,这两种说法不一样吗?

标签: c#cssselenium

解决方案


https://www.selenium.dev/selenium/docs/api/dotnet/html/M_OpenQA_Selenium_By_ClassName.htm

两者完全相同,第二个在引擎盖下将类转换为 .class 表示法

当您有疑问时,请转到 hithub 并搜索源代码。

您可以在以下位置获取 By 类的源代码:

https://github.com/SeleniumHQ/selenium/blob/dbd00caf7b8dddce075679453cce648a573a97d1/dotnet/src/webdriver/By.cs

通过 css

    public static By CssSelector(string cssSelectorToFind)
    {
        if (cssSelectorToFind == null)
        {
            throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null.");
        }

        By by = new By(CssSelectorMechanism, cssSelectorToFind);
        by.description = "By.CssSelector: " + cssSelectorToFind;
        return by;
    }

按类名:

public static By ClassName(string classNameToFind)
        {
            if (classNameToFind == null)
            {
                throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null.");
            }

            string selector = "." + By.EscapeCssSelector(classNameToFind);
            if (selector.Contains(" "))
            {
                // Finding elements by class name with whitespace is not allowed.
                // However, converting the single class name to a valid CSS selector
                // by prepending a '.' may result in a still-valid, but incorrect
                // selector. Thus, we short-ciruit that behavior here.
                throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
            }

            By by = new By(CssSelectorMechanism, selector);
            by.description = "By.ClassName[Contains]: " + classNameToFind;
            return by;
        }

所以两者都是相同的,但 by.class 名称将有额外的编码行,因此需要更多的秒数。


推荐阅读