Skip to content

Instantly share code, notes, and snippets.


tspspi/ Secret

Created Feb 10, 2020
What would you like to do?
Simple Selenium application using chromedriver in Java
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class TestProg {
public static void main(String[] args) {
try {
// Set path of chromedriver binary
System.setProperty("", "/usr/local/bin/chromedriver");
// Create the driver
WebDriver driver = new ChromeDriver();
// Fetch a webpage. For example use slashdot
Now we add a delay. Note that this is required
for JS heavy pages in any case to let scripts
Since our testpage doesn't have such problems
we could use a way shorter delay - but we set
a long one in any case to allow the user to
see more.
// Handle cookie accept banner if present
try {
WebElement bannerElem = driver.findElement(By.xpath("//*[@id=\"cmpwelcomebtnyes\"]/a"));;
System.out.println("Clicked the cookie banner ...");
} catch(NoSuchElementException e) {
System.out.println("Didn't have to click the cookie banner ...");
// Fetch all headings and their links
List<WebElement> titles = driver.findElements(By.className("story-title"));
for(WebElement elem : titles) {
WebElement titleLink = elem.findElement(By.tagName("a"));
String strTitle = titleLink.getText();
String strHref = titleLink.getAttribute("href");
System.out.println(strTitle + " + " + strHref);
} catch(Exception e) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.