working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,003 snippets matching: selenium

    public by sukhjinderkahlon modified Mar 9, 2016  325946  6  5  0

    How to Work with Excel Files Using Apache POI

    This code will work as a utility to read and write excel files using Apache POI Library. 3.13
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class ExcelUtils {
    
    	private static HSSFSheet ExcelWSheet;
    	private static HSSFWorkbook ExcelWBook;
    	private static HSSFCell Cell;
    
    	private static HSSFRow Row;
    	
    	private static String filePath;
    	public static void setExcelFile(String Path,String SheetName) throws Exception {
    
    			try {
    
       			// Open the Excel file
    				filePath=Path;
    
    			FileInputStream ExcelFile = new FileInputStream(Path);
    
    			// Access the required test data sheet
    
    			ExcelWBook = new HSSFWorkbook(ExcelFile);
    
    			ExcelWSheet = ExcelWBook.getSheet(SheetName);
    			
    
    			} catch (Exception e){
    
    				throw (e);
    
    			}
    
    	}
    
    	//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    
        public static String getCellData(int RowNum, int ColNum) throws Exception{
    
    			try{
    
      			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
    
      			String CellData = Cell.getStringCellValue();
    
      			return CellData;
    
      			}catch (Exception e){
    
    				return"";
    
      			}
    
        }
    
    
        
      //This method is to write in the Excel cell, Row num and Col num are the parameters
    
    	public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception	{
    
    			try{
    
      			Row  = ExcelWSheet.getRow(RowNum);
    
    			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    
    			if (Cell == null) {
    
    				Cell = Row.createCell(ColNum);
    
    				Cell.setCellValue(Result);
    
    				} else {
    
    					Cell.setCellValue(Result);
    
    				}
    
      // Constant variables Test Data path and Test Data file name
    
      				FileOutputStream fileOut = new FileOutputStream(filePath);
    
      				ExcelWBook.write(fileOut);
    
      				fileOut.flush();
    
    					fileOut.close();
    
    				}catch(Exception e){
    
    					throw (e);
    
    			}
    
    		}
    
    	
    }
              

    public by sukhjinderkahlon modified Mar 9, 2016  247416  2  4  0

    Selenium IsElementExists

    This code will find whether the element is present or not
    public static boolean isExistsElement(WebDriver driver, By by){
    		
    		    try {
    		        driver.findElement(by);
    		    } catch (NoSuchElementException e) {
    		        return false;
    		    }
    		    return true;
    			}            

    public by sukhjinderkahlon modified Mar 9, 2016  6005  30  6  0

    Extent Report For Selenium Java

    This code will work with Extent Report Utility for Java, Selenium, TestNG.
    //Download Jars from below website
    //http://relevantcodes.com/extentreports-for-selenium/
    import java.io.File;
    import java.io.IOException;
    
    import org.apache.commons.io.FileUtils;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;
    
    import com.relevantcodes.extentreports.DisplayOrder;
    import com.relevantcodes.extentreports.ExtentReports;
    
    	public class ReportFactory {
    		private static ExtentReports reporter;
    		
    		
    		public static ExtentReports getReporter() {
    			if (reporter == null) {
    				reporter = new ExtentReports("Report.html", true, DisplayOrder.NEWEST_FIRST);
    			}
    			return reporter;
    		}
    				
    		
    		//Close Reporter
    		
    		public static void closeReporter() {
    			if (reporter != null) {
    				reporter.flush();
    				reporter.close();
    			}
    		}
    		
    		//Capture ScreenShot
    		public static String CaptureScreen(WebDriver driver, String ImagesPath)
    		{
    		    TakesScreenshot oScn = (TakesScreenshot) driver;
    		    File oScnShot = oScn.getScreenshotAs(OutputType.FILE);
    		 File oDest = new File(ImagesPath+".jpg");
    		 try {
    		      FileUtils.copyFile(oScnShot, oDest);
    		 } catch (IOException e) {System.out.println(e.getMessage());}
    		 return ImagesPath+".jpg";
    		        }
    		
    		
    
    	}//End of class
    
    
    
    //Using of Extent in TestNG
    import org.testng.annotations.AfterSuite;
    import org.testng.annotations.Test;
    
    import com.relevantcodes.extentreports.ExtentReports;
    import com.relevantcodes.extentreports.ExtentTest;
    import com.relevantcodes.extentreports.LogStatus;
    
    import Damco.Project.ReportFactory;
    
    
    
    public class NewTest {
    	
    	
    private ExtentReports reporter =  ReportFactory.getReporter();
    private boolean status;
    	
    	@Test
    	public void Login()
    	{
    		ExtentTest testReporter = reporter.startTest(this.getClass().getSimpleName()+ " Login", "This is a simple simpleTest001");
    		testReporter.log(LogStatus.INFO, "Starting test simpleTest001");
    		int a = 100;
    		int b = 30;
    		status=false;
    		if(status ){
    		testReporter.log(LogStatus.INFO, "Loading the value of a to " + a);
    		testReporter.log(LogStatus.PASS, "Loading the value of b to " + b);
    		
    		}
    		else{
    			testReporter.log(LogStatus.INFO, "Failed to Loading the value of a to " + a);
    			testReporter.log(LogStatus.FAIL, "FAILED due some reason" + b);
    			
    			}
    		reporter.endTest(testReporter);
    	}
    
    	@Test
    	public void simpleTest002()
    	{
    		ExtentTest testReporter = reporter.startTest("simpleTest002", "This is a simple simpleTest001");
    		testReporter.log(LogStatus.INFO, "Starting test simpleTest002");
    		int a = 100;
    		int b = 30;
    
    		testReporter.log(LogStatus.INFO, "Loading the value of a to " + a);
    		testReporter.log(LogStatus.PASS, "Loading the value of b to " + b);
    		reporter.endTest(testReporter);
    		
    	}
    	
    	@Test
    	public void Register() throws Exception
    	{
    		ExtentTest testReporter = reporter.startTest("Register", "This is a simple simpleTest001");
    		testReporter.log(LogStatus.INFO, "Starting test simpleTest002");
    		int a = 100;
    		int b = 30;
    
    		testReporter.log(LogStatus.INFO, "Loading the value of a to " + a);
    		testReporter.log(LogStatus.PASS, "Loading the value of b to " + b);
    		reporter.endTest(testReporter);
    		
    
    		
    		
    	}
    	
    	
    	@AfterSuite
    	public void afterSuite()
    	{
    		reporter.close();
    	}
    	
    	
    }
    
    
    

    public by sukhjinderkahlon modified Mar 9, 2016  4249  2  6  1

    Selenium FluentWait

    // This method will return WebElement After Given wait           
    public static WebElement FindWithWait(WebDriver driver,By locator, int seconds) throws Exception{
    		// Sleep until the Element we want is visible or n seconds is over
    		WebElement element=null;
    		
    		//Because if implict wait is set then fluint wait will not work
    		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    		try{
    					FluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
    							.withTimeout(seconds, TimeUnit.SECONDS)
    							.pollingEvery(200, TimeUnit.MILLISECONDS)
    							.ignoring(NoSuchElementException.class)
    							.ignoring(StaleElementReferenceException.class)
    							.ignoring(WebDriverException.class);
    									 
    				element=fluentWait.until(
    							
    							ExpectedConditions.visibilityOfElementLocated(locator)
    							
    							);
    				return element;
    					
    		} catch(Exception e){
    			
    			throw new Exception("Timeout reached when searching for element! Time: " + seconds+" seconds " +"\n" +e.getMessage());
    			
    		}
    		finally {
    			driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    		}
    		
    	}
    
    	            

    public by huanshuai modified Jan 7, 2015  4215  3  6  0

    Flask Web Test using Selenium

    import time
    from unittest import TestCase
    from flask import url_for
    from selenium import webdriver
    
    from learnpython.app import app
    
    class TestViewsWithSelenium(TestCase):
        def setUp(self):
            self.browser = webdriver.Firefox()
            app.testing = True
            self._ctx = app.test_request_context()
            self._ctx.push()
    
        def tearDown(self):
            self._ctx.pop()
            self.browser.quit()
    
        def test_index(self):
            index_url = self.url('page', name='index')
    
            self.browser.get(self.url('/'))
            self.assertEqual(self.browser.current_url, index_url)
            time.sleep(1)
    
            element = self.browser.find_element_by_link_text('Learn Python')
            self.assertEqual(element.get_attribute('href'), index_url)
    
        def test_static(self):
            self.browser.get(self.url('static', filename='css/screen.css'))
            self.browser.get(self.url('static', filename='does_not_exists.exe'))

    public by hamidmousavi modified Feb 18, 2017  2032  2  4  1

    universal wrapper to make sure an element is visible

     public static boolean isElementPresentAndDisplayed(RemoteWebDriver driver, final WebElement element) {
            try {
                return element.isDisplayed();
            } catch (NoSuchElementException e) {
                return false;
            }
        }
    
    ....
    
      Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                        .withTimeout(timeoutSeconds, TimeUnit.SECONDS)
                        .pollingEvery(1, TimeUnit.SECONDS)
                        .ignoring(NoSuchElementException.class)
                        .ignoring(StaleElementReferenceException.class)
                        .ignoring(InvalidElementStateException.class);
                try {
                    return wait.until(drv -> {
                        final List<WebElement> foundElements = drv.findElements(by);
                        if (foundElements.size() > 0) {
                            for (WebElement element : foundElements) {
                                if (isElementPresentAndDisplayed(driver, element)) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    });
                } catch (TimeoutException e) {
                    return false;
                }

    public by Dan Nguyen modified Mar 20, 2016  2120  0  3  0

    Using Selenium and Python to screenshot a javascript-heavy page

    Using Selenium and Python to screenshot a javascript-heavy page: selenium-screenshotting.md
    # Using Selenium and Python to screenshot a javascript-heavy page
    
    As websites become more JavaScript heavy, it's harder to automate things like screenshotting for archival purposes. I've seen examples and suggestions to use [PhantomJS for visual testing/archiving of websites](http://j4n.co/blog/batch-rendering-screenshots-with-phantomjs), but have run into issues such as the [non-rendering of webfonts](http://squallssck.github.io/blog/2013/03/07/about-how-to-make-phantomjs-support-google-web-fonts/). I've never tried out [Selenium](http://selenium-python.readthedocs.org/api.html) until today...and while I'm not thinking about performance implications yet, Selenium seems far more accurate than PhantomJS...which makes sense since it actually opens a real browser. And it's not too hard to script to do complex interactions: here's an [example of how to log in to Twitter, write a tweet, upload an image, and send a tweet via Selenium and DOM element selection](https://gist.github.com/dannguyen/8a6fa49253c1d6a0eb92)...Obviously, you shouldn't be automating Twitter via browser when the API and [tweepy](http://docs.tweepy.org/en/v3.5.0/) are so much better for that, though it is fun to watch the browser go through the steps without you touching a thing.
    
    The example snippet below, which is not particularly well coded, opens up YouTube's homepage and clunkily scrolls to the bottom, triggering the AJAX events that load video previews below the browser fold. It then "clicks" the __Load more__ button, scrolls to the bottom, then scrolls back up before taking a screenshot of the entire page:
    
    ~~~py
    from selenium import webdriver
    from time import sleep
    driver = webdriver.Firefox()
    driver.get("https://www.youtube.com")
    
    
    # scroll some more
    for isec in (4, 3, 2, 1):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight / %s);" % isec)
        sleep(1)
    
    # load more
    sleep(2)
    print("push Load more...")
    driver.find_element_by_css_selector('button.load-more-button').click()
    
    print("wait a bit...")
    sleep(2)
    
    print("Jump to the bottom, work our way back up")
    for isec in (1, 2, 3, 4, 5):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight / %s);" % isec)
        sleep(1)
    
    driver.execute_script("window.scrollTo(0, 0)")
    print("Pausin a bit...")
    sleep(2)
    print("Scrollin to the top so that the nav bar isn't funny looking")
    driver.execute_script("window.scrollTo(0, 0);")
    
    
    sleep(1)
    print("Screenshotting...")
    # screenshot
    driver.save_screenshot("/tmp/youtube.com.jpg")
    ~~~
    
    # Result
    
    ![image](https://cloud.githubusercontent.com/assets/121520/13907240/2ac81e4e-eea7-11e5-8188-f279d87b77c0.png)
    
    
    

    public by hamidmousavi modified Feb 18, 2017  1620  0  4  0

    Selenium TryFindElement

    public void Test()
    {
        IWebDriver driver = new FirefoxDriver();
        IWebElement element = null;
        if (TryFindElement(By.CssSelector("div.logintextbox"), out element)
        {
            bool visible = IsElementVisible(element);
            if  (visible)
            {
                // do something
            }
        }
    }
    
    public bool TryFindElement(By by, out IWebElement element)
    {
        try
        {
            element = driver.FindElement(by);
        }
        catch (NoSuchElementException ex)
        {
            return false;
        }
        return true;
    }
    
    public bool IsElementVisible(IWebElement element)
    {
        return element.Displayed && element.Enabled;
    }

    public by hamidmousavi modified Feb 18, 2017  1603  0  5  0

    This method will return WebElement After Given wait

    // This method will return WebElement After Given wait           
    public static WebElement FindWithWait(WebDriver driver,By locator, int seconds) throws Exception{
    		// Sleep until the Element we want is visible or n seconds is over
    		WebElement element=null;
    		
    		//Because if implict wait is set then fluint wait will not work
    		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    		try{
    					FluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
    							.withTimeout(seconds, TimeUnit.SECONDS)
    							.pollingEvery(200, TimeUnit.MILLISECONDS)
    							.ignoring(NoSuchElementException.class)
    							.ignoring(StaleElementReferenceException.class)
    							.ignoring(WebDriverException.class);
    									 
    				element=fluentWait.until(
    							
    							ExpectedConditions.visibilityOfElementLocated(locator)
    							
    							);
    				return element;
    					
    		} catch(Exception e){
    			
    			throw new Exception("Timeout reached when searching for element! Time: " + seconds+" seconds " +"\n" +e.getMessage());
    			
    		}
    		finally {
    			driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    		}
    		
    	}

    public by yourfriendcaspian modified Sep 2, 2017  167  1  2  0

    Instructions for installing the most popular webdrivers, and then the latest version of the standalone Selenium server

    Instructions for installing the most popular webdrivers, and then the latest version of the standalone Selenium server: selenium-instructions.md
    # Steps For Setting Up Selenium And The Webdrivers
    
    ### Install The Firefox Geckodriver
    
    * Download [the latest Geckodriver for Firefox](https://github.com/mozilla/geckodriver/releases)
    * then `mv` that file to `/usr/local/bin/geckodriver` and `sudo chmod +x /usr/local/bin/geckodriver`
    * make sure you have `"webdriver.firefox.profile" : "geckodriver",` in your `nightwatch.json` file if you are using it
    
    ### Install The Chromedriver
    
    * Download the latest version [from the Chrome site](https://sites.google.com/a/chromium.org/chromedriver/downloads)
    * unzip it if it is a zip file
    * then `mv` that file to `/usr/local/bin/chromedriver` and `sudo chmod +x /usr/local/bin/chromedriver`
    
    ### Install the Safari Driver
    
    * Download the `SafariDriver.safariextz` [from the release site](http://selenium-release.storage.googleapis.com/index.html?path=2.45/)
    * Double click on the file and it will open in Safari
    * Accept the file as trusted
    * It will now show in your extensions
    
    ### Build the latest Selenium binary
    
    * `git clone git@github.com:SeleniumHQ/selenium.git`
    * `cd selenium`
    * `./go clean release`
    * `cd build/dist`
    * You can now run the server with the following: `java -jar selenium-server-standalone-3.0.0-beta1.jar`
    * _you may have a server of a different name depending on when you read this tutorial_
    
    ### Running the server
    
    * cd to the directory where you build the jar file
    * run: `java -jar selenium-server-standalone-3.0.0-beta1.jar`
    
    You can also alias the function in a `~/.bashrc` or `~/.zshrc` with:
    
    ```sh
    alias selenium="java -jar /path/to/build/dist/folder/selenium-server-standalone-3.0.0-beta1.jar"
    ```
    
    Remember: _You may have a server of a different name depending on when you read this tutorial_
    
    
    • Public Snippets
    • Channels Snippets