Menu

Script example: Clicking a list of elements

This step clicks a series of elements by executing a series of XPath lookups. If there were 3 elements to click, their XPaths would  be:

//*[@id="surveyQuestions"]/table/tbody/tr[2]/td[2]/span
//*[@id="surveyQuestions"]/table/tbody/tr[3]/td[2]/span
//*[@id="surveyQuestions"]/table/tbody/tr[4]/td[2]/span

There should be at least one element found, so it returns an error if none are found. It uses findElements() instead of findElement() because findElements() does not throw an exception if nothing is found. This makes it easy to catch all other exceptions and report them errors. If it finds more than one element with a single query, then something is wrong with the XPath, so it also reports this as an error.

function execute(context)
    {
    var index = 2;
    var elements = null;
    var num_found = 0;
    while (true)
        {
        try
            {
            var xpath = '//*[@id="surveyQuestions"]/table/tbody/tr[' + index + ']/td[2]/span';
            context.logMessage('looking for ' + xpath);
            elements = context.getDriver().findElements(By.xpath(xpath));
            if (elements.size() === 0)
                break;  // no more to click
            if (elements.size() > 1)
                return "Found " + elements.size() + " elements using XPath: " + xpath;
            num_found++;
            elements.get(0).click();
            }
        catch (error)
            {
            return error.toString();
            }
        index++;
        }
    if (num_found === 0)
        return "None found!";
    return null;
    }

Copyright © 2019 Web Performance, Inc.

A Durham web design company

×

(1) 919-845-7601 9AM-5PM EST

Just complete this form and we will get back to you as soon as possible with a quote. Please note: Technical support questions should be posted to our online support system.

About You
What you Need