以下實例示範如何使用net.URL 類別的URL() 建構子來抓取網頁:
/* author by w3cschool.cc Main.java */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.w3cschool.cc"); 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(); }}
以上程式碼執行輸出結果為(網頁的原始程式碼,儲存在目前目錄下的data.html 檔案中) :
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8"/>……
以上就是Java 實例- 網頁抓取的內容,更多相關內容請關注PHP中文網(www.php.cn)!