Home > Web Front-end > CSS Tutorial > Upgrade Your Project with CSS Selector and Custom Attributes

Upgrade Your Project with CSS Selector and Custom Attributes

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-16 09:20:37
Original
889 people have browsed it

Upgrade Your Project with CSS Selector and Custom Attributes

This article was originally published by TestProject. Thank you for supporting the partners who made SitePoint possible.

Selenium WebDriver's element selector is one of the core components of the automation framework and the key to interacting with any web application. In this review of automated element selectors, we will discuss various strategies, explore their capabilities, weigh their pros and cons, and ultimately recommend the best selector strategy—in combination with custom properties of the CSS selector.

Key Points

  • Selenium WebDriver's element selector is essential for interacting with any web application. The best selector strategy is to combine custom properties of the CSS selector, as it combines ease of use, versatility, online support, documentation, and performance.
  • Custom attributes and CSS selectors allow automation engineers to locate specific elements without creating complex element selectors. However, this requires collaboration between QA and the development team to add custom properties that can be used in the application.
  • XPath is a versatile and powerful element selector strategy that selects any element in the page, whether you have a class and ID available or not. However, XPath performs poorly in Internet Explorer.
  • ID and class element selectors are least affected by changes in the application structure. However, if the developer directly changes the ID or class used in automation, it will affect your tests.
  • The use of tag names, link text, partial link text and names as element selector strategies is limited and is not recommended to be widely adopted throughout the automation framework. They should only be used without additional selector options available, such as custom tags or IDs.

Selenium Element Selector

Choose the best element selector strategy is critical to the success of automation efforts and ease of maintenance. Therefore, when selecting a selector, ease of use, versatility, online support, documentation, and performance should be considered. Carefully considering the right selector strategy will pay off in the future with easy-to-maintenance automation.

Just as the technical aspects of the element selector should be considered, the culture of the organization should be considered. A mature culture of collaboration between developers and QA will achieve higher levels of success when implementing element selectors in automation. This not only benefits organizations by laying the foundation for collaboration in other areas of the software development lifecycle, but also goes beyond automation efforts themselves.

All code samples will use Python and Selenium WebDriver commands, but are generally applicable to any programming language and framework.

HTML Example:

I will use the HTML snippet of the following navigation menu as an example in each section:

<div id="main-menu">
  <div class="menu"><a href="https://www.php.cn/link/7878b14e9d762184301b06f3f609ead7">Home</a></div>
  <div class="menu"><a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe">Shop</a>
    <div class="submenu">
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/gizmo">Gizmo</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/widget">Widget</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/sprocket">Sprocket</a>
    </div>
  </div>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Don't recommend: tag name, link text, partial link text and name

I won't spend much time on this because they are all very limited in use. They are often not a good choice for widespread adoption throughout the automation framework. They address specific needs that can be easily addressed using other element selector strategies. Use these only if you have specific needs to deal with special circumstances. Even then, most special cases are not special enough to use these. You will use these without additional selector options available, such as custom tags or IDs.

Example:

Using tag names, you can select all the large number of elements that match the tag names you provide. This is of limited use because it only works if you need to select a large number of elements of the same type. The following example returns all 4 div elements in the sample HTML.

<div id="main-menu">
  <div class="menu"><a href="https://www.php.cn/link/7878b14e9d762184301b06f3f609ead7">Home</a></div>
  <div class="menu"><a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe">Shop</a>
    <div class="submenu">
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/gizmo">Gizmo</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/widget">Widget</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/sprocket">Sprocket</a>
    </div>
  </div>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

You can use the following example to select the link. As you can see, they can only locate anchor tags and the text of these anchor tags:

driver.find_elements(By.TAG_NAME, "div")
Copy after login
Copy after login
Copy after login
Copy after login

Finally, you can select elements by name attribute, but as you see in the sample HTML, there is no tag with name attribute. This is a common problem in almost any application, because it is very common to add a name attribute to every HTML attribute. If the main menu element has a name attribute like this:

driver.find_elements(By.LINK_TEXT, "Home")
driver.find_elements(By.PARTIAL_LINK_TEXT, "Sprock")
Copy after login
Copy after login

You can select it like this:

<div id="main-menu" name="menu"></div>
Copy after login
Copy after login

As you can see, these element selector strategies have limited use. The following methods are all better because they are more general and powerful.

Summary: Tag name, link text, partial link text and name

Pros Disadvantages Easy to use Not widely used Extremely limited use may not be applicable in some cases

Recommended: XPath

XPath is a versatile and powerful element selector strategy. This is also my personal preference and favorite. XPath can select any element in the page, whether you have classes and IDs available or not (although without classes or IDs, it is difficult to maintain and sometimes fragile). This option is especially common because you can select the parent element. XPath also has many built-in functions that allow you to customize element selection.

However, versatility brings complexity. Given that XPath can do a lot, its learning curve is also steeper than other element selector strategies. This can be compensated by excellent online documentation that is easily found. A good resource is the XPath tutorial found on W3Schools.com.

It should also be noted that there are trade-offs when using XPath. While you can select the parent element and use very general built-in functions, XPath performs poorly in Internet Explorer. This trade-off should be considered when selecting an element selector strategy. If you need to be able to select a parent element, you need to consider its impact on cross-browser testing in Internet Explorer. Essentially, it will take longer to run automated tests in Internet Explorer. If your application does not have a high Internet Explorer usage, this is a good choice because you might consider running less tests in Internet Explorer than other browsers. If your user base has a large Internet Explorer usage, you should only consider XPath if other better methods are not suitable for your organization.

Example:

If you have a requirement to select a parent element, you must select XPath. Here's how to do it: Using our example, suppose you want to locate the parent main-menu element based on an anchor element:

<div id="main-menu">
  <div class="menu"><a href="https://www.php.cn/link/7878b14e9d762184301b06f3f609ead7">Home</a></div>
  <div class="menu"><a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe">Shop</a>
    <div class="submenu">
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/gizmo">Gizmo</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/widget">Widget</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/sprocket">Sprocket</a>
    </div>
  </div>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This element selector will locate the first instance of the anchor label with id equal to "menu", and then locate the parent element with "/../". The result is that you will locate the main-menu element.

Summary: XPath

Pros Disadvantages Can select parent elements in IE Highly universal learning curve slightly steep Lots of online support

Recommended: ID and class

ID and class element selector are two different options in automation and perform different functions in the application. However, for considering which element selector strategy to use in automation, they differ very little, so we don't need to consider them separately. In an application, the "id" and "class" properties of an element (if defined) allow UI developers to manipulate and style the application. For automation, we use it to locate specific elements to interact in automation.

One of the benefits of using ID and class element selectors is that they are least affected by changes in the application structure. Suppose you want to create an XPath or CSS selector that relies on a chain of few elements and some child elements, what happens when a feature request breaks the chain by adding a new element? When using ID and class element selectors, you can locate specific elements instead of relying on page structure. You retain the robustness of automation without being too loose about changes. Changes should be detected by automation by creating test cases that focus on specific element locations. Changes should not break your entire automation suite. However, if the developer directly changes the ID or class used in automation, it will affect your tests.

If the application under test does not implement ID and class as part of development best practices, this element selector policy will not be available. This method is difficult to use if the HTML tag does not have the ID and class that you can use in automation.

Example:

In our example, if we want to select the top menu element, it looks like this:

driver.find_elements(By.TAG_NAME, "div")
Copy after login
Copy after login
Copy after login
Copy after login

If we want to select the first menu item, it looks like this:

<div id="main-menu">
  <div class="menu"><a href="https://www.php.cn/link/7878b14e9d762184301b06f3f609ead7">Home</a></div>
  <div class="menu"><a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe">Shop</a>
    <div class="submenu">
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/gizmo">Gizmo</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/widget">Widget</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/sprocket">Sprocket</a>
    </div>
  </div>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Summary: ID and class

Pros Disadvantages Easy to maintain Developers may change them, breaking automation Easy to learn Minimally affected by page structure changes

Best: Combined with custom properties of CSS selector

If your QA organization has a good collaborative relationship with the development team, you will most likely be able to use this best practice approach in automation. Using custom properties and CSS selectors to locate elements has multiple benefits for QA teams and organizations. For the QA team, this allows automation engineers to locate specific elements they need without creating complex element selectors. However, this requires the ability to add custom properties that automation teams can use in the application. To take advantage of this best practice approach, your development and QA team should work together to implement this strategy.

I want to take a moment to point out that the CSS selector method does not depend on custom properties. The CSS selector can locate any tags and properties in an HTML document like XPath.

Let's see what this method contains. To do this best, your automation team should understand what they want to target in automation. Working with developers (most likely front-end engineers), they will develop a custom attribute pattern that will be placed into every target the automation team needs to connect to. For this example, we append the 'tid' attribute to the target element.

A technical point to be emphasized here is a limitation of the CSS selector. They intentionally do not allow parent elements to be selected like XPath. This is done to avoid infinite loops in CSS styles on web pages. While this is a good thing for web design, it is a limitation for using it as an automated element selector strategy. Fortunately, this limitation can be avoided with custom properties implemented by developers. QA should request appropriate custom attributes so that there is no need to select the parent element.

If you want to select this policy without using custom properties, you are still on the right track. For example, you can locate links in the Shop submenu using the following methods:

driver.find_elements(By.TAG_NAME, "div")
Copy after login
Copy after login
Copy after login
Copy after login

This strategy will enable automation engineers to create reliable automation that is easy to maintain and does not break due to unrelated changes in the UI. Choosing this strategy is the best way to do it. Not only will it become an automation solution that is easy to maintain, it will also encourage collaboration between the development team and the QA team.

Example:

Implementing a custom property in our example HTML will produce the following results:

driver.find_elements(By.LINK_TEXT, "Home")
driver.find_elements(By.PARTIAL_LINK_TEXT, "Sprock")
Copy after login
Copy after login

Please note the new properties in some elements. We created a new property that does not conflict with any standard HTML attributes, called "tid". With this custom property, we can use the CSS selector to locate it:

<div id="main-menu" name="menu"></div>
Copy after login
Copy after login

Suppose you want to select all links in the menu, whether it is a top menu item or a submenu. Using the CSS selector, you can create highly general element selectors:

<div id="main-menu">
  <div class="menu"><a href="https://www.php.cn/link/7878b14e9d762184301b06f3f609ead7">Home</a></div>
  <div class="menu"><a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe">Shop</a>
    <div class="submenu">
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/gizmo">Gizmo</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/widget">Widget</a>
      <a href="https://www.php.cn/link/f775ec264c01adf8189da19ec86676fe/sprocket">Sprocket</a>
    </div>
  </div>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

The purpose of "*=" is to perform wildcard searches for the value "-link" in the tid field of any element. Put it after the #main-menu ID specifier, which focuses the search scope of the element within the main menu.

If you want to select this policy without using custom properties, you are still on the right track. For example, you can locate links in the Shop submenu using the following methods:

driver.find_elements(By.TAG_NAME, "div")
Copy after login
Copy after login
Copy after login
Copy after login

This strategy will enable automation engineers to create reliable automation that is easy to maintain and not interrupted by unrelated changes in the UI. Choosing this strategy is the best way to do it. Not only will it become an automation solution that is easy to maintain, it will also encourage collaboration between the development team and the QA team.

Summary: In combination with custom properties of CSS selector

Pros Disadvantages Easy to learn Initial efforts to build collaborative relationships with development teams Lots of online support Universal Excellent performance in all browsers

Conclusion

There are some good options for implementing enterprise standard element selector strategies in the automation framework. Options such as tag names or link text should be avoided unless it is your only option. XPath, ID, and class selectors are a good way. By far the best way is to implement custom properties and locate them using the CSS selector. This also encourages collaboration between the development team and the QA team.

The following are the options for side-by-side comparison:

✓ – Yes / – Part ✗ – No

标签名称、链接文本(等) XPath ID 和类 结合 CSS 选择器的自定义属性
易于使用
在线支持
通用性
性能
易于维护
鼓励协作

FAQs about custom properties of CSS selector

What are CSS selector custom properties?

CSS Selector Custom Attributes is a powerful feature in CSS that allows developers to select and style elements based on their attribute values. This is especially useful when you want to apply a specific style to elements that share public attributes but may not share the same tag name or class. For example, you can use a custom attribute selector to style all elements with "active" data attributes regardless of their tag name or class.

How to customize properties using CSS selector?

To customize properties with the CSS selector, you need to use square brackets [] in the CSS selector. In parentheses, you specify the attribute and value to select. For example, to select all elements with the "active" data attribute, you will use the selector [data-active]. You can then apply any desired style to these elements.

Can you use CSS selector custom properties with any properties?

Yes, you can use CSS selector custom properties with any properties. This includes standard HTML attributes such as "class" and "id" as well as any custom data attributes that you may have added to the element.

What are the different types of CSS property selectors?

There are several types of CSS property selectors. The most basic type is the exact match selector, which selects elements based on the exact match of its attribute values. There are also selectors for matching the beginning, ending, or any part of the property value. Additionally, there are selectors for matching elements with specific attributes regardless of their value.

Can you use CSS selector custom properties for all browsers?

All modern browsers (including Chrome, Firefox, Safari, and Edge) support CSS selector custom properties. However, they may not be supported by older versions of these browsers or other less common browsers. It is best to test your CSS in multiple browsers for compatibility.

How to use CSS selector custom properties to improve site performance?

CSS Selector Custom Properties can help improve website performance by reducing the amount of CSS you need to write. By selecting elements based on their attributes, you can apply styles to multiple elements at once without writing a separate CSS for each element. This can make your CSS more efficient and easier to maintain.

Can you use CSS selector custom properties in combination with other selectors?

Yes, you can use CSS selector custom properties in combination with other selectors. For example, you can use a custom attribute selector in combination with a class selector to select only elements with specific classes and specific attributes.

What are some common use cases for custom properties of CSS selectors?

CSS selector custom attributes are usually used to style elements based on their state or functions. For example, you can use a custom property selector to style all disabled buttons or all required form fields. They can also be used for theme settings by applying different styles according to the data-theme attribute.

How does CSS Selector custom properties compare to other CSS selectors?

CSS selector Custom properties provide greater flexibility than many other CSS selectors. While other selectors are limited to selecting elements based on their tag name, class, or ID, a custom attribute selector can select elements based on any attribute. This makes them a powerful tool for setting up complex web pages.

Are there any disadvantages of using CSS selector to customize properties?

One potential drawback of customizing properties with CSS selectors is that they can make your CSS more complex. If you use a large number of custom property selectors, it may be difficult to understand and maintain your CSS. However, this can be mitigated by careful planning and organization.

The above is the detailed content of Upgrade Your Project with CSS Selector and Custom Attributes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template