Finding Web Objects Using CSS Selectors

Applies to TestComplete 15.40, last modified on July 05, 2022
Information in this topic applies to web and hybrid mobile applications.

Typically, 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).

You can also use these CSS selectors in your TestComplete tests to search for web elements on a web page to simulate user actions over them. To search for web elements by using CSS selectors, you can use the following methods:

The difference between them is that the FindElements and QuerySelectorAll methods return an array of all matching elements, while the rest of them return the first element that matches the search expression. You can find more comparison information on these methods in Find Web Objects.

CSS Selector Syntax

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.

For a complete reference, see the W3C Selectors Level 3 Specification.

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.

Examples

FindElement example

The following example shows how you can use the FindElement method to find web elements by using CSS selectors:

JavaScript, JScript

function Test()
{
  …
  var browser = Sys.Browser();
  var page = browser.Page("*services.smartbear.com/samples/TestComplete*/smartstore/");

  var textbox = page.FindElement("#instasearch");
  var searchbutton = page.FindElement(".instasearch-button");
  …
}

Python

def Test():
  …
  browser = Sys.Browser()
  page = browser.Page("*services.smartbear.com/samples/TestComplete*/smartstore/")

  textbox = page.FindElement("#instasearch")
  searchbutton = page.FindElement(".instasearch-button")
  …

VBScript

Sub Test()
  …
  Set browser = Sys.Browser()
  Set page = browser.Page("*services.smartbear.com/samples/TestComplete*/smartstore/")

  Set textbox = page.FindElement("#instasearch")
  Set searchbutton = page.FindElement(".instasearch-button")
  …
End Sub

DelphiScript

procedure Test();
var browser, page, textbox, searchbutton;
begin
  …
  browser := Sys.Browser();
  page := browser.Page('*services.smartbear.com/samples/TestComplete*/smartstore/');

  textbox := page.FindElement('#instasearch');
  searchbutton := page.FindElement('.instasearch-button');
  …
end;

C++Script, C#Script

function Test()
{
  …
  var browser = Sys["Browser"]();
  var page = browser["Page"]("*services.smartbear.com/samples/TestComplete*/smartstore/");

  var textbox = page["FindElement"]("#instasearch");
  var searchbutton = page["FindElement"](".instasearch-button");
  …
}
QuerySelectorAll 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 (Classic)

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 (Legacy)

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

Find Web Objects
Access Native Web Attributes and Methods
QuerySelector Method (Page Objects)
Classic Web Testing

Highlight search results