selenium First project in selenium with Java Working Example in Selenium


Example

Now that we know the basics of Selenium, we can make our own project. For this example, we'll be making a program, which finds the Newest questions on stack-overflow.

We start easy, lets open stack-overflow.

public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "path of the exe file\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https:stackoverflow.com");
    Thread.sleep(3000);
    driver.quit();
}

Now, if you look at the source of the page, you find that all questions, are a tags, with an className of question-hyperlink. However, since there are multiple questions, we use a List of WebElement, instead of WebElement. Thus, we can do

public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "path to chromedriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https:stackoverflow.com");
    List<WebElement> list = driver.findElements(By.className("question-hyperlink"));
}

Now, we need to get the href attribute of the a tag, which has the link of the question. To do this, we can use getAttribute("href") on the each WebElement, like

public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "path to chromedriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https:stackoverflow.com");
    List<WebElement> list = driver.findElements(By.className("question-hyperlink"));
    System.out.println(list.size());
    list.forEach(e->System.out.println(e.getAttribute("href")));
    driver.quit();
}

This prints out the links of the top-questions on Stack-overflow.