How to use FirefoxDriver class of org.openqa.selenium.firefox package

Best Selenium code snippet using org.openqa.selenium.firefox.FirefoxDriver

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.iselsoft.easyium;
2
3import org.openqa.selenium.Capabilities;
4import org.openqa.selenium.firefox.FirefoxBinary;
5import org.openqa.selenium.firefox.FirefoxOptions;
6import org.openqa.selenium.firefox.FirefoxProfile;
7
8public class FirefoxDriver extends WebDriver {
9
10    public FirefoxDriver() {
11        super(new org.openqa.selenium.firefox.FirefoxDriver());
12    }
13
14    public FirefoxDriver(FirefoxOptions options) {
15        super(new org.openqa.selenium.firefox.FirefoxDriver(options));
16    }
17
18    public FirefoxDriver(FirefoxBinary binary) {
19        super(new org.openqa.selenium.firefox.FirefoxDriver(binary));
20    }
21    
22    public FirefoxDriver(FirefoxProfile profile) {
23        super(new org.openqa.selenium.firefox.FirefoxDriver(profile));
24    }
25
26    public FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile) {
27        super(new org.openqa.selenium.firefox.FirefoxDriver(binary, profile));
28    }
29
30    public FirefoxDriver(Capabilities desiredCapabilities) {
31        super(new org.openqa.selenium.firefox.FirefoxDriver(desiredCapabilities));
32    }
33
34    public FirefoxDriver(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
35        super(new org.openqa.selenium.firefox.FirefoxDriver(desiredCapabilities, requiredCapabilities));
36    }
37
38    public FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities capabilities) {
39        super(new org.openqa.selenium.firefox.FirefoxDriver(binary, profile, capabilities));
40    }
41
42    public FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
43        super(new org.openqa.selenium.firefox.FirefoxDriver(binary, profile, desiredCapabilities, requiredCapabilities));
44    }
45    
46    @Override
47    public WebDriverType getWebDriverType() {
48        return WebDriverType.FIREFOX;
49    }
50}
51
Full Screen
copy
1package com.workout;
2
3import org.openqa.selenium.WebDriver;
4import org.openqa.selenium.chrome.ChromeDriver;
5import org.openqa.selenium.firefox.*;
6import org.junit.Test;
7import org.openqa.selenium.*;
8import org.openqa.selenium.By;
9import org.openqa.selenium.WebElement;
10import org.openqa.selenium.firefox.FirefoxBinary;
11import org.openqa.selenium.firefox.FirefoxDriver;
12import org.openqa.selenium.firefox.FirefoxOptions;
13import org.openqa.selenium.By;
14import org.openqa.selenium.WebDriver;
15import org.openqa.selenium.WebElement;
16import org.openqa.selenium.firefox.FirefoxBinary;
17import org.openqa.selenium.firefox.FirefoxDriver;
18import org.openqa.selenium.firefox.FirefoxProfile;
19import org.openqa.selenium.remote.DesiredCapabilities;
20import org.openqa.selenium.remote.RemoteWebDriver;
21import java.io.IOException;
22import org.openqa.selenium.Keys;
23import org.openqa.selenium.WebDriver;
24import org.openqa.selenium.chrome.ChromeOptions;
25import org.openqa.selenium.chrome.ChromeDriver;
26
27import org.openqa.selenium.firefox.FirefoxOptions;
28
29
30import org.junit.*;
31import static org.junit.Assert.*;
32
33import java.io.File;
34
35import org.junit.experimental.categories.Category;
36
37import java.util.concurrent.TimeUnit;
38
39public class IntTest {
40static WebDriver driver;
41@Test
42public void TestRun()
43{
44	/*FirefoxBinary firefoxBinary = new FirefoxBinary();
45        firefoxBinary.addCommandLineOptions("--headless");
46        System.setProperty("webdriver.gecko.driver", "/usr/bin/geckodriver");
47        FirefoxOptions firefoxOptions = new FirefoxOptions();
48        firefoxOptions.setBinary(firefoxBinary);
49        FirefoxDriver driver = new FirefoxDriver();
50        driver = new FirefoxDriver(firefoxOptions);*/
51
52	//driver = new FirefoxDriver(firefoxOptions);
53	System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver");
54	//WebDriver driver= new ChromeDriver(new ChromeDriverService.Builder().usingPort(65530).build());
55    ChromeOptions chromeOptions = new ChromeOptions();
56    chromeOptions.addArguments("--headless");
57    chromeOptions.addArguments("--no-sandbox");
58    chromeOptions.addArguments("--disable-dev-shm-usage");
59    WebDriver driver = new ChromeDriver(chromeOptions);
60	driver.get("http://localhost:9090/WorkOut/index.jsp");
61	System.out.println(driver.getTitle()); //Titel of the webpage
62	driver.findElement(By.id("userName")).sendKeys("[email protected]"); //Enter the email
63	driver.findElement(By.id("userPw")).sendKeys("bsp"); //Enter the Password 
64	driver.findElement(By.id("login_btn1")).click(); //Click login Button
65	assertTrue(driver.getPageSource().contains("GOOD THINGS COME TO THOSE WHO SWEAT")); //Check the text in the webpage
66	driver.findElement(By.xpath("/html/body/div/div[1]/button")).click(); //select options
67	driver.findElement(By.xpath("/html/body/div/div[1]/div/a[1]")).click(); //Select the DropDown Element
68	//driver.findElement(By.id("item")).sendKeys("13"); //Enter the Value
69	//driver.findElement(By.id("submit")).click();
70	assertTrue(driver.getPageSource().contains("Enter the Count to Store")); //Check the Value
71	//driver.findElement(By.xpath("/html/body/div[1]/div/button")).click(); //Clear The Screen
72	driver.findElement(By.id("submit2")).click(); //Logout
73	System.out.println("*************" + driver.getTitle() + "*************"); //Print the Webpage Title
74	driver.quit();
75}
76@Test
77public void SignUp()
78{
79	/*FirefoxBinary firefoxBinary = new FirefoxBinary();
80        firefoxBinary.addCommandLineOptions("--headless");
81        System.setProperty("webdriver.gecko.driver", "/usr/bin/geckodriver");
82        FirefoxOptions firefoxOptions = new FirefoxOptions();
83        firefoxOptions.setBinary(firefoxBinary);
84        FirefoxDriver driver = new FirefoxDriver();
85        driver = new FirefoxDriver(firefoxOptions);*/
86	//driver = new FirefoxDriver(firefoxOptions);
87	System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver");
88    ChromeOptions chromeOptions = new ChromeOptions();
89    chromeOptions.addArguments("--headless");
90    chromeOptions.addArguments("--no-sandbox");
91    chromeOptions.addArguments("--disable-dev-shm-usage");
92    WebDriver driver = new ChromeDriver(chromeOptions);
93	driver.get("http://localhost:9090/WorkOut/Signup.jsp?");
94	System.out.println(driver.getTitle());
95	assertTrue(driver.getPageSource().contains("Workout Tracker"));
96	System.out.println("*************" + driver.getTitle() + "*************");
97	driver.quit();
98}
99}
100
Full Screen
copy
1package profile;
2
3import org.openqa.selenium.Capabilities;
4import org.openqa.selenium.WebDriver;
5import org.openqa.selenium.firefox.FirefoxBinary;
6import org.openqa.selenium.firefox.FirefoxDriver;
7import org.openqa.selenium.firefox.FirefoxProfile;
8import org.openqa.selenium.firefox.internal.ProfilesIni;
9
10public class BrowserProfile {
11	
12	public static void main(String[] args) {
13		
14		
15		ProfilesIni profile = new ProfilesIni();
16		FirefoxProfile myprofile = profile.getProfile("ProfileWithCert");
17		FirefoxDriver driver = new FirefoxDriver((Capabilities) myprofile);
18	}
19
20}
21
Full Screen
copy
1Selenium.executeScript("window.scrollBy(0,450)", "");
2
Full Screen
copy
1JavascriptExecutor jse = (JavascriptExecutor)driver;
2jse.executeScript("window.scrollBy(0,250)");
3
Full Screen
copy
1JavascriptExecutor js = ((JavascriptExecutor) driver);
2js.executeScript("window.scrollTo(0,100"); 
3
Full Screen
copy
1driver.get(url)
2# Get scroll height
3last_height = driver.execute_script("return document.body.scrollHeight")
4try_times = 0
5while True:
6    # Scroll down to bottom
7    driver.execute_script("window.scrollBy(0,2000)")
8
9    # Wait to load page
10    time.sleep(scroll_delay)
11    # Calculate new scroll height and compare with last scroll height
12    new_height = driver.execute_script("return document.body.scrollHeight")
13
14    if last_height == new_height:
15        try_times += 1
16
17    if try_times > 3:
18        try_times = 0
19        break
20    last_height = new_height
21
Full Screen
copy
1((JavascriptExecutor) driver).executeScript("scroll(0,300)");
2
Full Screen
copy
1JavascriptExecutor jse = ((JavascriptExecutor) driver);
2jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");
3
Full Screen
copy
1const element = await driver.findElement(...)
2await driver.executeScript("arguments[0].scrollIntoView(true);", element)
3await driver.sleep(500);
4
Full Screen
copy
1WebDriver driver = new ChromeDriver();
2JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
3jsExecuter.executeScript(window.scrollTo(0,document.body.scrollHeight));
4
Full Screen
copy
1WebDriver driver = new ChromeDriver();
2JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
3jsExecuter.executeScript(window.scrollTo(0,document.body.scrollTop));
4
Full Screen
copy
1WebDriver driver = new ChromeDriver();
2JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
3jsExecuter.executeScript(window.scrollTo(0,document.body.scrollLeft));
4
Full Screen
copy
1WebDriver driver = new ChromeDriver();
2JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
3jsExecuter.executeScript(window.scrollTo(0,500));
4
Full Screen
copy
1IWebElement body = Driver.FindElement(By.TagName("body"));
2
3IAction scrollDown = new Actions(Driver)
4    .MoveToElement(body, body.Size.Width - 10, 15) // position mouse over scrollbar
5    .ClickAndHold()
6    .MoveByOffset(0, 50) // scroll down
7    .Release()
8    .Build();
9
10scrollDown.Perform();
11
Full Screen
copy
1Actions dragger = new Actions(driver);
2WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("//*[@id='jobreslist_outercontainer']/div/div[2]/div"));
3
4// drag downwards
5int numberOfPixelsToDragTheScrollbarDown = 50;
6for (int i = 10; i < 500; i += numberOfPixelsToDragTheScrollbarDown) {
7    try {
8        // this causes a gradual drag of the scroll bar, 10 units at a time
9        dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release().perform();
10        Thread.sleep(1000L);
11    } catch(Exception e1) {}
12}
13
14// now drag opposite way (downwards)
15numberOfPixelsToDragTheScrollbarDown = -50;
16for (int i = 500; i > 10; i += numberOfPixelsToDragTheScrollbarDown) {
17    // this causes a gradual drag of the scroll bar, -10 units at a time
18    dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release().perform();
19    Thread.sleep(1000L);
20}
21        
22
Full Screen
copy
1JavascriptExecutor js = ((JavascriptExecutor) driver);
2
Full Screen
copy
1js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
2
Full Screen
copy
1js.executeScript("window.scrollTo(0, -document.body.scrollHeight);");
2
Full Screen
copy
1Robot robot = new Robot();
2robot.keyPress(KeyEvent.VK_PAGE_DOWN);
3robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
4
Full Screen
copy
1 // This  will scroll page 400 pixel vertical
2  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");
3
Full Screen
copy
1je.executeScript("arguments[0].scrollIntoView(true);",element);
2
Full Screen
copy
1JavascriptExecutor js = ((JavascriptExecutor) driver);
2js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
3
Full Screen
copy
1WebDriver driver = new FirefoxDriver();
2JavascriptExecutor jse = (JavascriptExecutor)driver;
3jse.executeScript("window.scrollBy(0,250)");
4
Full Screen
copy
1jse.executeScript("window.scrollBy(0,-250)");
2OR,
3jse.executeScript("scroll(0, -250);");
4
Full Screen
copy
1jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");
2
Full Screen
copy
1driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);
2
Full Screen
copy
1Robot robot = new Robot();
2robot.keyPress(KeyEvent.VK_CONTROL);
3robot.keyPress(KeyEvent.VK_END);
4robot.keyRelease(KeyEvent.VK_END);
5robot.keyRelease(KeyEvent.VK_CONTROL);
6
Full Screen
copy
1WHEN ELEMENT IS FOUND WITHOUT ANY DELAY :
2>>> WITH implicit = 30, explicit = 20  :::::  Wait time = 0
3
4
5WHEN ELEMENT IS NOT FOUND :
6a. When implicit wait = explicit wait.
7>>> WITH implicit = 10, explicit = 10  :::::  Wait time = 10. ***WITH EXCEPTION*** : NoSuchElementException
8
9b. When implicit wait > explicit wait.
10>>> WITH implicit = 30, explicit = 10  :::::  Wait time = 30. ***WITH EXCEPTION*** : NoSuchElementException
11
12c. When implicit wait < explicit wait.
13>>> WITH implicit = 10, explicit = 30  :::::  Wait time = 10. ***WITH EXCEPTION*** : NoSuchElementException
14
Full Screen
copy
1import org.openqa.selenium.By;
2import org.openqa.selenium.WebDriver;
3import org.openqa.selenium.WebElement;
4import org.openqa.selenium.chrome.ChromeDriver;
5import org.openqa.selenium.support.ui.ExpectedConditions;
6import org.openqa.selenium.support.ui.WebDriverWait;
7
8import java.text.SimpleDateFormat;
9import java.util.Date;
10import java.util.TimeZone;
11import java.util.concurrent.TimeUnit;
12
13/*
14 * Facing this chromedriver error after opening browser - [SEVERE]: Timed out receiving message
15 * from renderer: 0.100.
16 * */
17public class TimeTest {
18    static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
19    static final String URL = "https://www.redbus.in/";
20    static final String TIME_ZONE_NAME = "Europe/Madrid";
21    static final By validLoc = By.id("src");
22    static final By inValidLoc = By.id("invalid locator");
23    static WebDriver driver;
24
25        public static void main(String[] args) {
26            dateFormat.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_NAME));
27
28            //>>> Open chrome browser
29            System.setProperty("webdriver.chrome.driver", "C:/drivers/chromedriver.exe");
30            TimeTest.driver= new ChromeDriver();
31            driver.manage().window().maximize();
32
33            //>>> Test waiting logic.
34
35            System.out.println("\n\nWHEN ELEMENT IS FOUND WITHOUT ANY DELAY : ");
36            //mixing of implicit wait and explicit wait will not impact on webdriver behavior.
37            testWait(30, 20, validLoc, "");
38
39            System.out.println("\n\nWHEN ELEMENT IS NOT FOUND : ");
40            //Run the method multiple times. Wait time generally = 10 seconds, but sometimes = 20 seconds.
41            testWait(10, 10, inValidLoc, "a. When implicit wait = explicit wait.");
42
43            //Wait time always = implicit wait. Generally ?
44            testWait(30, 10, inValidLoc, "b. When implicit wait > explicit wait.");
45
46            //Wait time always = implicit wait. Generally ?
47            testWait(10, 30, inValidLoc, "c. When implicit wait < explicit wait.");
48
49            //>>> Close the browser.
50            driver.quit();
51        }
52
53
54        public static void testWait(int implicitWait, int explicitWait, By locator, String comment){
55            // setting implicit time
56            driver.manage().timeouts().implicitlyWait(implicitWait, TimeUnit.SECONDS);
57
58            // Loading a URL
59            driver.get(URL);
60
61            // defining explicit wait
62            WebDriverWait wait= new WebDriverWait(driver, explicitWait);
63            // Locating and typing in From text box.
64
65
66            Date start = new Date();
67            String waitStats = comment + "\n>>> WITH implicit = " + implicitWait + ", explicit = " + explicitWait +
68                    "  :::::  " ;//+ "Wait start = " + dateFormat.format(start)
69
70            String exceptionMsg = "";
71
72            try {
73                WebElement fromTextBox = wait.until(ExpectedConditions.visibilityOf(driver.findElement(locator)));
74            }catch (Exception ex){
75                exceptionMsg = ". ***WITH EXCEPTION*** : " + ex.getClass().getSimpleName();
76            }
77
78            Date end = new Date();
79            //waitStats += ", Wait end = " + dateFormat.format(end)
80            waitStats += "Wait time = " +
81                    TimeUnit.SECONDS.convert(end.getTime() - start.getTime(), TimeUnit.MILLISECONDS)
82                    + exceptionMsg + "\n";
83
84            System.out.println(waitStats);
85
86        }
87
88}
89
Full Screen
copy
1WebDriver driver = new FirefoxDriver();
2driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
3
Full Screen
copy
1WebDriver driver = new FirefoxDriver();
2WebDriverWait wait = new WebDriverWait(driver,30);
3
Full Screen
copy
1    1. Static Wait 
2    2. UnConditional Wait (No conditions are given)
3    3. Applicable throughout the program
4
Full Screen
copy
1driver.manage().timeout().implicitWait(20, TimeUnit.Seconds());
2
Full Screen
copy
1WebDriverWait wait=new WebDriverWait(driver, 20); wait.until(somecondition);
2
Full Screen
copy
1WebDriverWait _wait = new WebDriverWait(driver, new TimeSpan(0, 0, 2)); //waits 2 secs max
2_wait.Until(d => d.FindElement(By.Id("name")));
3//do your business on the element here :)
4
Full Screen
copy
1public WebElement fluentWait(final By locator) {
2    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
3        .withTimeout(30, TimeUnit.SECONDS)
4        .pollingEvery(5, TimeUnit.SECONDS)
5        .ignoring(NoSuchElementException.class);
6
7    WebElement foo = wait.until(
8        new Function<WebDriver, WebElement>() {
9            public WebElement apply(WebDriver driver) {
10                return driver.findElement(locator);
11            }
12        }
13    );
14
15    return foo;          
16};
17
Full Screen
copy
1WebDriver driver = new FirefoxDriver();
2driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
3driver.get("http://somedomain/url_that_delays_loading");
4WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
5
Full Screen
copy
1WebDriver driver = new FirefoxDriver();
2driver.get("http://somedomain/url_that_delays_loading");
3WebDriverWait wait = new WebDriverWait(driver, 10);
4WebElement myDynamicElement = wait.until(
5  ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
6
Full Screen
copy
1// clicking on view details 
2driver.findElement(By.id("")).click();
3// closing the pop up 
4driver.findElement(By.id("")).click();
5
6
7// and when you try to click on Add Item
8driver.findElement(By.id("")).click();
9// you get stale element exception as reference to add item is lost 
10// so to overcome this you have to re identify the locator strategy for add item 
11// Please note : this is one of the way to overcome stale element exception 
12
13// Step 1 please add a universal wait in your script like below 
14driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser
15
Full Screen
copy
1WebDriverWait wait = new WebDriverWait(driver, 40);
2wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid"))); // instead of id you can use cssSelector or xpath of your element.
3
Full Screen
copy
1wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
2
Full Screen
copy
1wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
2
Full Screen
copy
1WebDriverWait wait = new WebDriverWait(driver, 20);
2By addItem = By.xpath("//input[.='Add Item']");
3
4// get the "Add Item" element
5WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
6
7//trigger the reaload of the page
8driver.findElement(By.id("...")).click();
9
10// wait the element "Add Item" to become stale
11wait.until(ExpectedConditions.stalenessOf(element));
12
13// click on "Add Item" once the page is reloaded
14wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();
15
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)