Selenium Webdriver Waitforelementpresent When Javascript Refreshes

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

Selenium WebDriver waitForElementPresent when Javascript refreshes

WebDriverWait(driver, long_wait).until(
    EC.presence_of_element_located(find_element(driver, selector))
)
def waitForElementPresent(self, driver, selector):
    try:
        WebDriverWait(driver, 10, ignored_exceptions=[
            NoSuchElementException, StaleElementReferenceException
        ]).until(EC.presence_of_element_located(find_element(driver,     selector)))
    except NoSuchElementException:
        print("No such element, waititng again")
        self.waitForElementPresent(driver, selector)

    print("Returning normally")
    return
def waitForElementPresent(driver, selector):
    return WebDriverWait(driver, 60).until(EC.presence_of_element_located(selector))

element = waitForElementPresent(driver, (By.ID, "myid"))

Selenium WebDriver wait till element is displayed

Browse other questions tagged javascript node.js selenium-webdriver or ask your own question. The Overflow Blog Developers vs the difficulty bomb (Ep. 459)

//dependencies
var webdriver = require('selenium-webdriver'),
    util = require('util'),
    _ = require('underscore');

var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
var branchName =  _.isUndefined(process.argv[3]) ? 'branch' : process.argv[3], 
    hostName = _.isUndefined(process.argv[2]) ? 'localhost' : process.argv[2],
    appTmpl = 'http://%s/%s',
    username = 'xxxx',
    password = 'xxxx';
var appUrl = util.format(appTmpl, hostName, branchName);

driver.get(appUrl);
driver.findElement(webdriver.By.name("username")).sendKeys(username);
driver.findElement(webdriver.By.name("password")).sendKeys(password);
driver.findElement(webdriver.By.name("login_button")).click();
driver.quit();
    C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1643
      throw error;
            ^
NoSuchElementError: no such element
  (Session info: chrome=37.0.2062.103)
  (Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64)
    at new bot.Error (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\atoms\error.js:109:18)
    at Object.bot.response.checkResponse (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\atoms\response.js:106:9)
    at C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:277:20
    at C:\Work\study\selenium\node_modules\selenium-webdriver\lib\goog\base.js:1243:15
    at webdriver.promise.ControlFlow.runInNewFrame_ (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1539:20)
    at notify (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:362:12)
    at notifyAll (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:331:7)
    at resolve (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:309:7)
    at fulfill (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:429:5)
    at C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1406:10
==== async task ====
WebDriver.findElement(By.name("username"))
    at webdriver.WebDriver.schedule (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:268:15)
    at webdriver.WebDriver.findElement (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:711:17)
    at Object.<anonymous> (C:\Work\study\selenium\test.js:15:8)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
driver.wait(function () {
    return driver.isElementPresent(webdriver.By.name("username"));
}, timeout);
let el = await driver.findElement(By.id(`import-file-acqId:${acqId}`));
await driver.wait(until.elementIsVisible(el),100);
await el.sendKeys(file);
driver.wait(until.elementLocated(By.name('username')), 5 * 1000).then(el => {
    el.sendKeys(username);
});
const element = By.id('element');
driver.wait(until.elementLocated(element));
const whatElement = driver.findElement(element);
driver.wait(until.elementIsVisible(whatElement), 5000).click();
function isItThere(driver, element){

    driver.findElement(webdriver.By.id(element)).then(function(webElement) {
            console.log(element + ' exists');
        }, function(err) {
            if (err.state && err.state === 'no such element') {
                console.log(element + ' not found');
            } else {
                webdriver.promise.rejected(err);
            }
        });
}
 var el = driver.wait(until.elementLocated(By.name('username')));
el.click();
(async function() {
  let url = args[0];
  await driver.get(url);
  driver.quit();
})();
const waitFind = (locator) => {
    return driver.findElement(async () => {
        await driver.wait(until.elementLocated(locator));
        return driver.findElement(locator);
    });
}
StaleElementReferenceError: stale element reference: element is not attached to the page document  (Session info: chrome=83.0.4103.106)
async clickonitem( driver, itemname ) {
    const strftime = require('strftime');
    var trycounter = 0;
    var timeout = 500;
    var success;
    do {
      try {
        trycounter++;
        success = true;
        console.log( strftime('%F %T.%L'), "Finding #" + trycounter + " " + itemname );
        var item = await driver.wait( until.elementLocated( By.xpath( '//input[@name="' + itemname +'"]' ) ), 
                        timeout );
        console.log( strftime('%F %T.%L'), "Found or Timeout #" + trycounter );
        //await item.click();
        await driver.wait( item.click(), 
                        timeout );
        console.log( strftime('%F %T.%L'), "Click #" + trycounter + " " + itemname );
      } 
      catch(err) {
        success = false;
        //this.log( "Error #" + trycounter + " " + itemname + "\n" +err );
        this.log( strftime('%F %T.%L'), "Error #" + trycounter + " " + itemname + " waiting: " + timeout );
        await wait( timeout );
        continue;
      }

    } while( !success && trycounter < 5 );
}       
        async wait( ms ) {
          return new Promise((resolve) => {
            setTimeout(resolve, ms);
          });
        }

clickonitem( driver, "login_button" );
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplctWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait of 5 secs
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement m = driver.findElement(By.tagName("h4"));
      System.out.println("Element text is: " + m.getText());
      driver.quit();
   }
}
WebDriverWait w= (new WebDriverWait(driver,5 ));
w.until(ExpectedConditions.presenceOfElementLocated(By.id("txt")));
w.until(ExpectedConditions.visibilityOfElementLocated (By.name("nam-txt")));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExplicitWt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/index.htm");
      //explicit wait condition - presenceOfElementLocated
      WebDriverWait w= (new WebDriverWait(driver, 7));
      w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='Library']")));
      WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
      m.click();
      //explicit wait condition - visibilityOfElementLocated
      w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
      WebElement n = driver.findElement(By.linkText("Subscribe to Premium"));
      String s = n.getText();
      System.out.println("Text is: " + s);
      driver.quit();
   }
}

JavaScript & Selenium WebDriver With Example

Nowadays, all browser supports Java Script. So we can run the Java Script in any browser by following the below steps: Open any browser. Got to the console tab by pressing the F12 key or right-click and select inspect. Type the Java Script in the console tab and hit enter to run the Java Script. Add Java Screenshot.

Object executeScript(String arg0, Object arg1);
Object executeAsyncScript(String arg0, Object arg1);
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class JavaScriptInSelenium 
{
   public static void main(String[] args) 
   {
      System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
      WebDriver driver= new ChromeDriver();

      driver.manage().window().maximize();

      JavascriptExecutor js= (JavascriptExecutor)driver;
      js.executeScript("console.log('Hello.');");

      driver.get("https://www.softwaretestingo.com/");
   }
}
JavascriptExecutor js= (JavascriptExecutor)driver;
import org.openqa.selenium.chrome.ChromeDriver;
public class JavaScriptInSelenium
{
   public static void main(String[] args)
   {
      System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
      ChromeDriver driver= new ChromeDriver();
      driver.manage().window().maximize();
      driver.executeScript("console.log('Hello.');");
      driver.get("http://www.softwaretestingo.com/");
   }
}
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaScriptInSelenium
{
   public static void main(String[] args)
   {
      System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
      RemoteWebDriver driver= new ChromeDriver();
      driver.manage().window().maximize();
      driver.executeScript("console.log('Hello.');");
      driver.get("http://www.softwaretestingo.com/");
   }
}
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaScriptInSelenium
{
   public static void main(String[] args)
   {
      System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
      ChromeDriver driver= new ChromeDriver();
      driver.manage().window().maximize();
      driver.executeScript("console.log('Hello '+arguments[0] +' Welcome to '+arguments[1]);","User","SoftwareTestingo");
   }
}
driver.executeScript(“console.log(‘Hello.’);”);
function()
{
   console.log("Hello");
}
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaScriptInSelenium
{
   public static void main(String[] args)
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      ChromeDriver driver = new ChromeDriver();
      driver.manage().window().maximize();
      Object response = driver.executeScript("return 1===2");
      System.out.println(response);
   }
}
import java.util.Date;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
public class ExecuteAsynJavascriptCommandsInSelenium
{
   public static void main(String[] args)
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      ChromeDriver driver = new ChromeDriver();
      driver.manage().window().maximize();
      System.out.println("Start time: " + new Date());
      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js= (JavascriptExecutor)driver;
      js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);");
      System.out.println("End time: " + new Date());
      driver.quit();
   }
}
import java.util.Date;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
public class ExecuteAsynJavascriptCommandsInSelenium
{
   public static void main(String[] args)
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      ChromeDriver driver = new ChromeDriver();
      driver.manage().window().maximize();
      System.out.println("Start time: " + new Date());
      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js= (JavascriptExecutor)driver;
      js.executeScript("window.setTimeout(arguments[arguments.length - 1], 5000);");
      System.out.println("End time: " + new Date());
      driver.quit();
   }
}
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaScriptInSelenium 
{
   public static void main(String[] args) 
   {

      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      driver.manage().window().maximize();

      driver.get("https://www.makemytrip.com/");

      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js= (JavascriptExecutor)driver;

      // Down casting to WebElement because executeScript return a type of Object
      WebElement element= (WebElement) js.executeScript("return document.getElementById('searchBtn')");

      // Getting text
      String text= element.getText();
      System.out.println("Text: "+text);
   }
}
import java.util.List;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaScriptInSelenium 
{
   public static void main(String[] args) 
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      driver.manage().window().maximize();
      driver.get("https://www.makemytrip.com/");

      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js= (JavascriptExecutor)driver;

      // Down casting to List<WebElement> because executeScript return a type of Object
      List<WebElement> element= (List<WebElement>) js.executeScript("return document.getElementsByClassName('non-pot')");

      // Getting text
      System.out.println(element.size());
   }
}
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CaptureFullWebPage 
{

   public static String CaptureScreenShotWithTestStepName(WebDriver driver, String testStepsName)
   {
      try{
         // down casting WebDriver to use getScreenshotAs method.
         TakesScreenshot ts= (TakesScreenshot)driver;
         // capturing screen shot as output type file
         File screenshotSRC= ts.getScreenshotAs(OutputType.FILE);
         // Defining path and extension of image
         String path=System.getProperty("user.dir")+"/ScreenCapturesPNG/"+testStepsName+System.currentTimeMillis()+".png";
         // copying file from temp folder to desired location
         File screenshotDest= new File(path);
         FileUtils.copyFile(screenshotSRC, screenshotDest);
         return path;
      }
      catch(Exception e)
      {
         System.out.println("Some exception occured." + e.getMessage());
         return "";
      }
   }
   public static void main(String[] args) throws InterruptedException
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      driver.manage().window().maximize();
      driver.get("http://www.softwaretestingo.com/");

      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js = (JavascriptExecutor) driver;

      // It returns height of view part. You can say it as page height. When you click on page down key
      // Page scroll by one page.
      long pageHeight= (long)js.executeScript("return window.innerHeight");
      System.out.println("Page height: "+pageHeight);

      // It is how much you can scroll. It is height if you scroll, you will reach to bottom of page.
      long scrollableHeight= (long)js.executeScript("return document.body.scrollHeight");
      System.out.println("Total scrollable height: "+scrollableHeight);

      // Finding number of pages. Adding 1 extra to consider decimal part.
      int numberOfPages=(int) (scrollableHeight/pageHeight)+1;
      System.out.println("Total pages: "+numberOfPages);

      // Now scrolling page by page
      for(int i=0;i<numberOfPages;i++)
      {
         CaptureFullWebPage.CaptureScreenShotWithTestStepName(driver, "Page "+(i+1));
         js.executeScript("window.scrollBy(0,"+pageHeight+")");
         Thread.sleep(2000);
      }
   }
}
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TypeUsingJavascript 
{
   public static void main(String[] args) 
   {

      System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
      WebDriver driver= new ChromeDriver();

      driver.manage().window().maximize();
      driver.get("https://www.google.com/");

      WebElement searchBox= driver.findElement(By.name("q"));

      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js = (JavascriptExecutor) driver;

      // Setting value for "value" attribute
      js.executeScript("arguments[0].value='selenium'", searchBox);
   }
}
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TypeIntoHiddenElement 
{
   public static void main(String[] args) throws IOException 
   {
      System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
      WebDriver driver= new ChromeDriver();

      driver.manage().window().maximize();
      driver.get("file:///C://Users//amodm//Desktop//NewHidden.html");
      WebElement searchBox= driver.findElement(By.id("files"));

      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js = (JavascriptExecutor) driver;

      // Setting value for "style" attribute to make input tag visible
      js.executeScript("arguments[0].style.display='block';", searchBox);

      searchBox.sendKeys("F:\\Eclipse_WS\\softwaretestingo\\ScreenCapturesPNG\\TypeUsingJS.jpg");
   }
}

JavaScriptExecutor in Selenium WebDriver with Example

JavaScriptExecutor Methods. Example of executeAsyncScript. Example 1: Performing a sleep in the browser under test. Example of executeScript. 1) Example: Click a button to login and generate Alert window. 2) Example: Capture Scrape Data and Navigate to different pages. 3) Example: Scroll Downusing.

JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);
import java.util.concurrent.TimeUnit;		

import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				

    @Test		
    public void Login() 					
    {		
        		
        WebDriver driver= new FirefoxDriver();			

        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("http://demo.guru99.com/V4/");			
     
          //Maximize window		
          driver.manage().window().maximize();		
        		
          //Set the Script Timeout to 20 seconds		
          driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);			
             
          //Declare and set the start time		
          long start_time = System.currentTimeMillis();			
                   
          //Call executeAsyncScript() method to wait for 5 seconds		
          js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);");			
          		
         //Get the difference (currentTime - startTime)  of times.		
         System.out.println("Passed time: " + (System.currentTimeMillis() - start_time));					
                    		
    }		
}			
[TestNG] Running:		
C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-387352559\testng-customsuite.xml		
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).		
log4j:WARN Please initialize the log4j system properly.		
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.		
Passed time: 5022		
PASSED: Login		

===============================================		
    Default test		
    Tests run: 1, Failures: 0, Skips: 0		
===============================================
import org.openqa.selenium.By;		
import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.WebElement;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				


    @Test		
    public void Login() 					
    {		
        WebDriver driver= new FirefoxDriver();			
        		
        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("http://demo.guru99.com/V4/");			
        		
        WebElement button =driver.findElement(By.name("btnLogin"));			
        		
        //Login to Guru99 		
        driver.findElement(By.name("uid")).sendKeys("mngr34926");					
        driver.findElement(By.name("password")).sendKeys("amUpenu");					
        		
        //Perform Click on LOGIN button using JavascriptExecutor		
        js.executeScript("arguments[0].click();", button);
                                
        //To generate Alert window using JavascriptExecutor. Display the alert message 			
        js.executeScript("alert('Welcome to Guru99');");   
    		
    }		
}
import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				

    @Test		
    public void Login() 					
    {		
        WebDriver driver= new FirefoxDriver();			
        		
        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("http://demo.guru99.com/V4/");
			
        //Fetching the Domain Name of the site. Tostring() change object to name.		
        String DomainName = js.executeScript("return document.domain;").toString();			
        System.out.println("Domain name of the site = "+DomainName);					
          		
        //Fetching the URL of the site. Tostring() change object to name		
        String url = js.executeScript("return document.URL;").toString();			
        System.out.println("URL of the site = "+url);					
          		
       //Method document.title fetch the Title name of the site. Tostring() change object to name		
       String TitleName = js.executeScript("return document.title;").toString();			
       System.out.println("Title of the page = "+TitleName);					

        		
      //Navigate to new Page i.e to generate access page. (launch new url)		
      js.executeScript("window.location = 'http://demo.guru99.com/'");			
    }		
}
[TestNG] Running:		
  C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-467151014\testng-customsuite.xml		

log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).		
log4j:WARN Please initialize the log4j system properly.		
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.		
Domain name of the site = demo.guru99.com		
URL of the site = http://demo.guru99.com/V4/		
Title of the page = Guru99 Bank Home Page		
PASSED: Login		

===============================================		
    Default test		
    Tests run: 1, Failures: 0, Skips: 0
===============================================
import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				

    @Test		
    public void Login() 					
    {		
        WebDriver driver= new FirefoxDriver();			
        		
        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("http://moneyboats.com/");			
     
        //Maximize window		
        driver.manage().window().maximize();		
        		
        //Vertical scroll down by 600  pixels		
        js.executeScript("window.scrollBy(0,600)");			
    }		
}

Selenium Webdriver - JavaScript Executor

Selenium can execute JavaScript commands with the help of the method - execute_script. The JavaScript command to be executed is passed as a parameter to this method. The syntax for executing the Javascript commands with the help of execute_script method is as follows −. driver.execute_script ("window.scrollTo (0, document.body.scrollHeight);")


b = driver.find_element_by_id("txt")
driver.execute_script ("arguments[0].click();",b)

from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#click with JavaScript Executor
b = driver.find_element_by_link_text("Cookies Policy")
driver.execute_script ("arguments[0].click();",b)
print('Page title after click: '+ driver.title)
#driver quit
driver.quit()

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("https://www.tutorialspoint.com/index.htm")
#scroll to page bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Previous PostNext Post

Related code examples