Sample-Code

Every instance comes with some basic sample code. With this samples you can learn the most common browser operations. There are two language bindings pre-installed: Java and Python. Those are the most popular languages in Selenium development.

The below sample code is for Chrome on a Ubuntu server without a graphical user interface. Sample code for other OS and browser can be found on the virtual machines.



Init webdriver:

Before we start the Chrome browser, we specify some options. The first options tells Chrome to run in Headless mode, this means without a GUI. The second option sets the browser locale to English.
Afterwards we start Chrome via Chromedriver. Selenium 3 does not interact directly with the browser itself.
When it is ready, we tell the driver to wait 5 seconds in case an element can not be found after the page loaded. This can be the case for dynamic content of website. At last, we set the browser X and Y dimension in pixels.

options = COptions()
options.add_argument("--headless") # Runs Chrome in headless mode.
options.add_argument("--lang=en-GB") #remove this line if you want to set the browser locale to the region you launched this instance
driver = webdriver.Chrome(executable_path=r"/home/ubuntu/chromedriver", chrome_options=options)
 
driver.implicitly_wait(5) #general timeout for waiting on dynamic web elements
driver.set_window_size(1500, 700)
System.setProperty("webdriver.chrome.driver", "/home/ubuntu/chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--lang=en-GB"); //remove this line if you want to set the browser locale to the AWS region you launched this instance

WebDriver driver = new ChromeDriver(chromeOptions);

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //general timeout for waiting on dynamic web elements
driver.manage().window().setSize(new Dimension(1500,700)); //set window size

Navigate to URL:

We now navigate to this webpage using the driver.get() method.

driver.get("https://selenium-cloud.com/sample-code.html")
driver.get("https://selenium-cloud.com/sample-code.html");

Take a screenshot:

Let us take a screenshot to proove we are on the page. This also works in headless browser!

driver.save_screenshot('screenshot.png')
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("/home/ubuntu/java/screenshot.png"));

Click on element via XPath:

Before we can click an element on the page, we need to locate it. There are different methods to achieve this, the most common way is via XPath.
There are dozens of good tools to get the XPath of elements, Chrome has also one built-in.

Below you find a screenshot of the popular ChroPath plugin:


Learn more about XPath here

element = driver.find_element_by_xpath("//a[@id='java-tab1']") #relative XPath
element.click()
element = driver.find_element_by_xpath("/html[1]/body[1]/div[1]/ul[1]/li[1]/a[1]") #absolute XPath
element.click()
WebElement element = driver.findElement(By.xpath("//a[@id='java-tab1']")); //relative XPath
element.click();
System.out.println("Clicked on 'Java' under Init Webdriver");
element = driver.findElement(By.xpath("/html[1]/body[1]/div[1]/ul[1]/li[1]/a[1]")); //absolute XPath
element.click();

Click on element via class name:

Another way to locate web elements is to use their class names. The problem is, that a class name is generally used more than once on a page, so we get a list of web elements instead of a single one.

elements = driver.find_elements_by_class_name("nav-link") #this returns a list of all nav-link elements
elements[1].click() #click on second element in list, which is 'Documentation' in topbar
element = driver.findElements(By.className("nav-link")).get(1); //#click on second element in list, which is 'Documentation' in topbar
element.click();

Using browser back button:

This sample shows you how to use the back button of the browser. There is no built in function for that in Selenium, so we are going to use JavaScript.

driver.execute_script("window.history.go(-1)")
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.history.go(-1)");

Scroll down to specific element:

Same goes for scrolling a specific element into view. We first specify the element, then we use JavaScript to scroll that element into view.

element = driver.find_element_by_xpath("//input[@id='text-field']")
driver.execute_script("arguments[0].scrollIntoView(true);", element)
element = driver.findElement(By.xpath("//input[@id='text-field']"));
jse.executeScript("arguments[0].scrollIntoView(true);", element);

Send string to input field and open popup:

Now we type in some text into a text field. Afterwards we click on the button which opens a small popup.

element.send_keys("Sent from Selenium Headless Browser")
element = driver.find_element_by_xpath("//button[contains(text(),'Click me!')]")
element.click()
element.sendKeys("Sent from Selenium");
element = driver.findElement(By.xpath("//button[contains(text(),'Click me!')]"));
element.click();


Get text of element:

The last code block shows you, how you can pull out the visible text of an element.

element = driver.find_element_by_xpath("//div[@id='modalbody-text']")
text = element.text
element = driver.findElement(By.xpath("//div[@id='modalbody-text']"));
String text = element.getText();