Easy Tutorial
❮ File Dir Character Iswhitespace ❯

Java Example - Web Scraping

Java Examples

The following example demonstrates how to use the URL() constructor of the net.URL class to scrape a webpage:

Main.java File

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {
   public static void main(String[] args) 
   throws Exception {
      URL url = new URL("http://www.tutorialpro.org");
      BufferedReader reader = new BufferedReader
      (new InputStreamReader(url.openStream()));
      BufferedWriter writer = new BufferedWriter
      (new FileWriter("data.html"));
      String line;
      while ((line = reader.readLine()) != null) {
         System.out.println(line);
         writer.write(line);
         writer.newLine();
      }
      reader.close();
      writer.close();
   }
}

The above code outputs the following result (the source code of the webpage, stored in the "data.html" file in the current directory):

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8"/>……

Java Examples

❮ File Dir Character Iswhitespace ❯