Skip to content

Instantly share code, notes, and snippets.

@tspspi
Created February 10, 2020 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tspspi/7e4f1f42fab0c7f88e2d445a2bf21a76 to your computer and use it in GitHub Desktop.
Save tspspi/7e4f1f42fab0c7f88e2d445a2bf21a76 to your computer and use it in GitHub Desktop.
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;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestProg {
public static void main(String[] args) {
try {
// Set path of chromedriver binary
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
// Create the driver
WebDriver driver = new ChromeDriver();
// Fetch a webpage. For example use slashdot
driver.get("https://slashdot.org/");
/*
Now we add a delay. Note that this is required
for JS heavy pages in any case to let scripts
initialize.
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.
*/
Thread.sleep(5000);
{
// Handle cookie accept banner if present
try {
WebElement bannerElem = driver.findElement(By.xpath("//*[@id=\"cmpwelcomebtnyes\"]/a"));
bannerElem.click();
System.out.println("Clicked the cookie banner ...");
Thread.sleep(250);
} 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);
}
}
Thread.sleep(5000);
driver.quit();
} catch(Exception e) {
e.printStackTrace();
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment