Finding Web Objects Using CSS Selectors

Applies to TestComplete 14.20, last modified on September 11, 2019
Information in this topic applies to web and hybrid mobile applications.

This topic explains how you can search for the needed elements on the tested web page by the elements’ attributes and their values.

General Information

You can use Cascading Style Sheets (CSS) selectors to choose elements on an HTML page and style them. This is a very powerful and flexible tool that you can equally use for selecting several elements at once (say, all the images or all the text fragments on a page), as well as for selecting a specific element (like the "Contact me" link in the page footer).

TestComplete allows you to use CSS selectors when searching for objects on web pages, so, you can use the syntax you are familiar with. Besides, specifying elements in the same way as in CSS is extremely useful when you need to verify the style of your web site.

To search for web elements by using CSS selectors, you can use the QuerySelector and QuerySelectorAll methods. These methods accept a CSS selector as the input parameter and return the matching elements of the web page. The difference between them is that the QuerySelector method returns the first found match, while the QuerySelectorAll method returns an array of all matching elements. The methods are available for the Page object and its child objects.

The Example section of this topic demonstrates how you can use the QuerySelector and QuerySelectorAll methods to search for web page elements from your scripts. In keyword tests, you can call the QuerySelector or QuerySelectorAll method by using the Call Object Method or Run Code Snippet operation. Also, you can execute the entire script routine like the example below from your keyword test by using the Run Script Routine operation.

CSS Selector Syntax

This section describes the basics of using and constructing CSS selectors. For a complete reference, see the W3C Selectors Level 3 Specification.

With CSS selectors, you can search for web objects by their types, IDs, class names, attributes, position on the page and so on. The table below lists some of the most frequently used selectors:

Selector Syntax Description
Universal selector * Selects all the elements.
Type selectors element_name Defines the name of the elements to be selected.
ID selectors #ID_name Defines the identifier of the element to be selected. Identifiers are unique on a web page. An HTML document cannot have two elements with the same ID.
Class selectors .class_name Defines the class name of the elements to be selected.
Attribute selectors [attribute_name] Denotes all the elements of the web page that have the specified attribute. The actual value of the attribute is not important.
[attribute_name=atr_value] Denotes all the elements of the web page that have the specified attribute whose value is exactly "atr_value".
[attribute_name^=atr_value] Denotes all the elements with the specified attribute that begins with "atr_value".
[attribute_name$=atr_value] Denotes all the elements with the specified attribute that ends with "atr_value".
[attribute_name*=atr_value] Denotes all the elements that have the specified attribute whose value contains the substring "atr_value".
[attribute_name~=atr_value] Denotes all the elements that have the specified attribute whose value contains "atr_value" as a separate word.
Pseudo-class selectors :link All unvisited links
:visited All visited links
:hover All the elements in the mouse over state.
:focus The element that has focus.
:first-child All the elements that are the first child of their parents.
:nth-child(n) Every element that is the n-th child, regardless of the type of its parent.
:first-of-type Every element that is the first child of a parent of a particular type.
:nth-of-type(n) Every element that is the n-th child of a parent of a particular type.

Simple selectors can be combined and grouped to construct more complex conditions:

Combinator Syntax Description
Descendant combinator (whitespace) element_E element_F Selects element F that is located anywhere within element E.
Child combinator (>) element_E > element_F Selects element F that is a direct child of element E. Elements that are not direct children of the specified parent are not selected.
General sibling combinator (~) element_E ~ element_F Selects element F that is preceded by element E.
Adjacent sibling combinator (+) element_E + element_F Selects element F that is immediately preceded by element E.
Group combinator (,) element_Eelement_F Selects all E elements and all F elements.

The element and attribute names in search expressions are case-insensitive. However, the sought-for data are case-sensitive.

The two expressions below are equivalent:

div.nav
DIV.nav

These two expressions are different:

div.nav
div.NAV

To avoid problems, specify values in the case in which they are specified in the source code of the tested web page.

Tip: To explore the actual tree of web page elements, you can use the debugging tools provided by the web browser:
  • Internet Explorer 10 and later: select Tools | F12 Developer Tools from the main menu.

  • Mozilla Firefox: select Tools | Web Developer | Inspect from the main menu.

  • Google Chrome: select Tools | Developer Tools from the main menu.

Example

The example below demonstrates how you can use the QuerySelectorAll method in Google Chrome or Android WebView. It obtains all A elements that have the "nav-cat-main" class name. The sample code also outputs the inner text of the found elements.

Note: The only difference between scripts for web and hybrid mobile applications are in the way you obtain the Page object.

Web

JavaScript

function FindByCSSSelector()
{
var TestedPage, CSSSelector, arr, res, cnt;

  Browsers.Item(btChrome).Run("https://smartbear.com/");
  TestedPage = Sys.Browser().Page("*");

  CSSSelector = "a.nav-cat-main";
  
  // Call the function
  arr = TestedPage.QuerySelectorAll(CSSSelector);
  // Check the result    
  if (arr.length > 0)
    {
      // Matching elements were found
      Log.Message("Found " + intToStr(arr.length)+ " elements matching the CSS selector: " + CSSSelector);
      // Convert the array to the JScript-compatible format
      for (let i=0;i<arr.length;i++)
        {
          // Output the element's content
          Log.Message(arr[i].contentText);
        }
    }
  else
    {
      // No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector);
    }
}

JScript

function FindByCSSSelector()
{
var TestedPage, CSSSelector, arr, res, cnt, i;

  Browsers.Item(btChrome).Run("https://smartbear.com/");
  TestedPage = Sys.Browser().Page("*");

  CSSSelector = "a.nav-cat-main";
  
  // Call the function
  arr = TestedPage.QuerySelectorAll(CSSSelector).toArray();
  // Check the result    
  if (arr.length > 0)
    {
      // Matching elements were found
      Log.Message("Found " + intToStr(arr.length)+ " elements matching the CSS selector: " + CSSSelector);
      // Convert the array to the JScript-compatible format
      for (i=0;i<arr.length;i++)
        {
          // Output the element's content
          Log.Message(arr[i].contentText);
        }
    }
  else
    {
      // No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector);
    }
}

Python

def FindByCSSSelector():
  Browsers.Item[btChrome].Run("http://smartbear.com/");
  TestedPage = Sys.Browser().Page("*");

  CSSSelector = "a.nav-cat-main"; 
  
  # Call the function 
  res = TestedPage.QuerySelectorAll(CSSSelector);
  # Check the result
  cnt = BuiltIn.VarArrayHighBound(res,1);
    
  if (cnt > -1):
    # Matching elements were found 
    Log.Message("Found " + IntToStr(cnt+1)+ " elements matching the CSS selector: " + CSSSelector);
    for i in range (0, cnt-1):
      # Output the element's content
      Log.Message(res[i].contentText); 
  else:
      # No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector);

VBScript

Sub FindByCSSSelector
  Dim TestedPage, CSSSelector, res, cnt, i

  Browsers.Item(btChrome).Run("http://smartbear.com/")
  Set TestedPage = Sys.Browser().Page("*")

  CSSSelector = "a.nav-cat-main" 
  
  ' Call the function
  res = TestedPage.QuerySelectorAll(CSSSelector)
  ' Check the result
  cnt = BuiltIn.VarArrayHighBound(res,1)
    
  If cnt > -1 Then
      ' Matching elements were found
      Log.Message("Found " + IntToStr(cnt+1)+ " elements matching the CSS selector: " + CSSSelector)
      For i=0 To cnt
          ' Output the element's content
          Log.Message(res(i).contentText)
      Next
  Else
      ' No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector)
  End If
End Sub

DelphiScript

function FindByCSSSelector();
var TestedPage, CSSSelector, res, cnt, i;
begin
  Browsers.Item(btChrome).Run('http://smartbear.com/');
  TestedPage := Sys.Browser().Page('*');

  CSSSelector := 'a.nav-cat-main';
  
  // Call the function
  res := TestedPage.QuerySelectorAll(CSSSelector);
  // Check the result
  cnt := BuiltIn.VarArrayHighBound(res,1);
    
  if cnt > -1 then
    begin
      // Matching elements were found
      Log.Message('Found ' + intToStr(cnt+1)+ ' elements matching the CSS selector: ' + CSSSelector);
      for i:=0 to cnt do
        begin
          // Output the element's content
          Log.Message(res[i].contentText);
        end;
    end
  else
    begin
      // No matching elements were found
      Log.Warning('Did not find any elements matching the CSS selector: ' + CSSSelector);
    end;
end;

C++Script, C#Script

function FindByCSSSelector()
{
var TestedPage, CSSSelector, arr, res, cnt, i;

  Browsers["Item"](btChrome)["Run"]("http://smartbear.com/");
  TestedPage = Sys["Browser"]()["Page"]("*");

  CSSSelector = "a.nav-cat-main";
  
  // Call the function
  arr = TestedPage["QuerySelectorAll"](CSSSelector);
  // Check the result
  cnt = BuiltIn["VarArrayHighBound"](arr,1);
    
  if (cnt > -1)
    {
      // Matching elements were found
      Log["Message"]("Found " + intToStr(cnt+1)+ " elements matching the CSS selector: " + CSSSelector);
      // Convert the array to the JScript-compatible format
    var res = arr["toArray"]();
      for (i=0;i<=cnt;i++)
        {
          // Output the element's content
          Log["Message"](res[i]["contentText"]);
        }
    }
  else
    {
      // No matching elements were found
      Log["Warning"]("Did not find any elements matching the CSS selector: " + CSSSelector);
    }
}

Mobile

JavaScript

function FindByCSSSelector1()
{
  var CSSSelector, arr, res, cnt;

  // Select the mobile device
  Mobile.SetCurrent("MyDevice");

  // Obtain the WebView object and navigate to a web page
  // On Android devices
  var app = Mobile.Device().Process("smartbear.tctests.webbrowserapp");
  var page = app.RootLayout("").Layout("layoutTop").WebView("webview").Page("file:///android_asset/page1.html").ToUrl(url);
  // On iOS devices
  // var app = Mobile.Device().Process("SampleWebViewApp");
  // var page = app.Window(0).WebView(0).Page("http://www.example.com").ToUrl("http://smartbear.com/");

  CSSSelector = "a.nav-cat-main";
  
  // Call the function
  arr = TestedPage.QuerySelectorAll(CSSSelector);
  // Check the result
  if (arr.length > 0)
    {
      // Matching elements were found
      Log.Message("Found " + intToStr(arr.length)+ " elements matching the CSS selector: " + CSSSelector);
      // Convert the array to the JScript-compatible format
      for (let i=0;i<arr.length;i++)
        {
          // Output the element's content
          Log.Message(arr[i].contentText);
        }
    }
  else 
    {
      // No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector);
    }
}

JScript

function FindByCSSSelector1()
{
  var CSSSelector, arr, res, cnt, i;

  // Select the mobile device
  Mobile.SetCurrent("MyDevice");

  // Obtain the WebView object and navigate to a web page
  // On Android devices
  var app = Mobile.Device.Process("smartbear.tctests.webbrowserapp");
  var page = app.RootLayout("").Layout("layoutTop").WebView("webview").Page("file:///android_asset/page1.html").ToUrl(url);
  // On iOS devices
  // var app = Mobile.Device.Process("SampleWebViewApp");
  // var page = app.Window(0).WebView(0).Page("http://www.example.com").ToUrl("http://smartbear.com/");

  CSSSelector = "a.nav-cat-main";
  
  // Call the function
  arr = TestedPage.QuerySelectorAll(CSSSelector).toArray();
  // Check the result
  if (arr.length > 0)
    {
      // Matching elements were found
      Log.Message("Found " + intToStr(arr.length)+ " elements matching the CSS selector: " + CSSSelector);
      // Convert the array to the JScript-compatible format
      for (i=0;i<arr.length;i++)
        {
          // Output the element's content
          Log.Message(arr[i].contentText);
        }
    }
  else 
    {
      // No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector);
    }
}

Python

def FindByCSSSelector1():
  # Select the mobile device
  Mobile.SetCurrent("MyDevice");

  # Obtain the WebView object and navigate to a web page 
  # On Android devices 
  app = Mobile.Device().Process("smartbear.tctests.webbrowserapp");
  page = app.RootLayout("").Layout("layoutTop").WebView("webview").Page("file:///android_asset/page1.html").ToUrl(url);
  # On iOS devices 
  # app = Mobile.Device().Process("SampleWebViewApp");
  # page = app.Window(0).WebView(0).Page("http://www.example.com").ToUrl("http://smartbear.com/");

  CSSSelector = "a.nav-cat-main"; 
  
  # Call the function 
  res = TestedPage.QuerySelectorAll(CSSSelector);
  # Check the result 
  cnt = BuiltIn.VarArrayHighBound(res,1);
    
  if (cnt > -1): 
    # Matching elements were found 
    Log.Message("Found " + IntToStr(cnt+1)+ " elements matching the CSS selector: " + CSSSelector);
    for i in range (0, cnt-1): 
      # Output the element's content 
      Log.Message(res[i].contentText); 
  else: 
    # No matching elements were found 
    Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector);

VBScript

Sub FindByCSSSelector1
  Dim TestedPage, app, CSSSelector, res, cnt, i

  ' Select the mobile device
  Mobile.SetCurrent("MyDevice")

  ' Obtain the WebView object and navigate to a web page
  ' On Android devices
  Set app = Mobile.Device.Process("smartbear.tctests.webbrowserapp")
  Set page = app.RootLayout("").Layout("layoutTop").WebView("webview").Page("file:///android_asset/page1.html").ToUrl ("http://smartbear.com/")
  ' On iOS devices
  ' Set app = Mobile.Device.Process("SampleWebViewApp")
  ' Set page = app.Window(0).WebView(0).Page("http://www.example.com").ToUrl (http://smartbear.com/)
  CSSSelector = "a.nav-cat-main"
  
  ' Call the function
  res = TestedPage.QuerySelectorAll(CSSSelector)
  ' Check the result
  cnt = BuiltIn.VarArrayHighBound(res,1)
    
  If cnt > -1 Then 
      ' Matching elements were found
      Log.Message("Found " + IntToStr(cnt+1)+ " elements matching the CSS selector: " + CSSSelector)
      For i=0 To cnt
          ' Output the element's content
          Log.Message(res(i).contentText)
      Next 
  Else 
      ' No matching elements were found
      Log.Warning("Did not find any elements matching the CSS selector: " + CSSSelector)
  End If 
End Sub 

DelphiScript

function FindByCSSSelector1();
var 
  app, TestedPage, CSSSelector, res, cnt, i;
begin 
  // Select the mobile device
  Mobile.SetCurrent('MyDevice');

  // Obtain the WebView object and navigate to a web page
  // On Android devices
  app := Mobile.Device.Process('smartbear.tctests.webbrowserapp');
  page := app.RootLayout('').Layout('layoutTop').WebView('webview').Page('file:///android_asset/page1.html').ToUrl(url);
  // On iOS devices
  // app := Mobile.Device.Process('SampleWebViewApp');
  // page := app.Window(0).WebView(0).Page('http://www.example.com').ToUrl('http://smartbear.com/');

  CSSSelector := 'a.nav-cat-main';
  
  // Call the function
  res := TestedPage.QuerySelectorAll(CSSSelector);
  // Check the result
  cnt := BuiltIn.VarArrayHighBound(res,1);
    
  if cnt > -1 then 
    begin 
      // Matching elements were found
      Log.Message('Found ' + intToStr(cnt+1)+ ' elements matching the CSS selector: ' + CSSSelector);
      for i:=0 to cnt do 
        begin 
          // Output the element's content
          Log.Message(res[i].contentText);
        end;
    end 
  else 
    begin 
      // No matching elements were found
      Log.Warning('Did not find any elements matching the CSS selector: ' + CSSSelector);
    end;
end;

C++Script, C#Script

function FindByCSSSelector1()
{
var CSSSelector, arr, res, cnt, i;
  
  // Select the mobile device
  Mobile["SetCurrent"]("MyDevice");

  // Obtain the WebView object and navigate to a web page
  // On Android devices
  var app = Mobile["Device"].Process("smartbear.tctests.webbrowserapp");
  var page = app["RootLayout"]("")["Layout"]("layoutTop")["WebView"]("webview")["Page"]("file:///android_asset/page1.html")["ToUrl"]("http://smartbear.com/")
  // On iOS devices
  // var app = Mobile["Device"].Process("SampleWebViewApp");
  // var page = app["Window"](0)["WebView"](0)["Page"]("http://www.example.com")["ToUrl"]("http://smartbear.com/")

 
  CSSSelector = "a.nav-cat-main";
  
  // Call the function
  arr = TestedPage["QuerySelectorAll"](CSSSelector);
  // Check the result
  cnt = BuiltIn["VarArrayHighBound"](arr,1);
    
  if (cnt > -1)
    {
      // Matching elements were found
      Log["Message"]("Found " + intToStr(cnt+1)+ " elements matching the CSS selector: " + CSSSelector);
      // Convert the array to the JScript-compatible format
    var res = arr["toArray"]();
      for (i=0;i<=cnt;i++)
        {
          // Output the element's content
          Log["Message"](res[i]["contentText"]);
        }
    }
  else 
    {
      // No matching elements were found
      Log["Warning"]("Did not find any elements matching the CSS selector: " + CSSSelector);
    }
}

See Also

About Finding Objects on Web Pages
Accessing Native Web Attributes and Methods
QuerySelector Method (Page Objects)
Testing Web Applications

Highlight search results