Help with script

Hello,

I am trying to capture all elements on a browser using $browser.findelements. But, I can’t seem to get text associated with the tags afterwards. Here is a sample code. I am not sure what I am missing here. Any help is much appreciated.

.then(function()
{
return $browser.findElements(By.tagName(“a”));
$browser.sleep(1000);
})
.then(function(elements){
for(var i=0;i<elements.length;i++)
{console.log(elements[i].getText());
}
});

Helo, @krishnachaitanyaredd: The element.getText() method does not return the text, it returns a promise. So you may not simply print the result of the function, you must specify a function to execute and receive the result. Here is how I would write it:

$browser.get('https://example.com/')
  .then(function(){
    return $browser.findElements($driver.By.tagName('a'))
      .then(function(elements) {
        return elements.forEach(function(element) {
          return element.getText()
            .then(function(text) {
              console.log(text);
            });
        });
      });
  });
3 Likes

Hello,

I have created a function but the problem is every time I call it it says document is not defined. Does anyone have an idea how can I resolve this ?

Code:

function companyNameToProductName (){
var company = document.querySelectorAll(“tr td.company img.img-responsive”) //get the company
var product = document.querySelectorAll(“tr td.product-name span[value]”) //get the product
var companyName;
var productName;
for(var x = 0; x < product.length; x++) {
companyName = company[x].getAttribute(“value”) //get the company value
productName = product[x].getAttribute(“value”) //get the product name value
product[x].innerHTML = companyName + " " + productName //output the companyName + productName on the page
}
}

The code will output this result:

Before Running the code:

After Running the code on dev tools:

The only problem is once I run it on new relic synthetics it keeps on showing an reference error that document is not defined.

Here is how I called it on synthetics:

.then(() => {
logger.log(31, “Click overview tab”)
return $browser.findElement(byXpath(’//*[@id=“dynatable”]/nav/ul/li[1]/a’)).click()
$browser.sleep(5000)
})
.then(() => {
logger.log(32, “Execute function”)
companyNameToProductName()
$browser.sleep(5000)
})

Note: I tried running the said code on katalon studio using the executeJavascript action and it works as expected

Thank you ! hoping that someone can help me with this :smile:

Hi, @vincent.benales: It looks like you want to run this script in the browser, rather than as part of an external Selenium script. If so, you might try passing it to $browser.executeScript().