java代碼實作網頁原始碼爬取
java代碼基于Eclipse簡單實作網頁原始碼爬取
哈哈,大家好!我是yanxiaolxy,前天四級英語考試考完了,作業也不多了,感覺整個人都變得輕松了許多,
今天給大家分享我的最新java學習行程--java網頁原始碼爬蟲,廢話不多說盤代碼,
僅需一頁代碼:
package 網站爬蟲2;
/**
* 爬取目標網頁源代碼示例
* @作者 YanXiaolxy
* @版本 2020.03
* @時間 2020年12月14日 下午1:14:14
*/
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class webHtmlCrawer {
public static void main(String[] args) {
newFile();
}
public static String getConnection() {
String path = "https://www.taobao.com/";
try {
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
InputStream xml = conn.getInputStream();
byte[] data = read(xml);
//System.out.println(xml);
return new String(data);
}else {
System.out.println("連接失敗!");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//讀取資料流,轉換為字串
public static byte[] read(InputStream xml) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = xml.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
xml.close();
return outputStream.toByteArray();
}
public static void newFile() {
String html = getConnection();
String dir = "D:/javafile/";//定義創建目錄位置
File contents = new File(dir);
contents.mkdirs();//創建檔案目錄
try {
byte bytes[] = {1, 2, 3, 4};
File file = new File("D:/javafile/test.txt");
//判斷檔案是否存在,如果不存在就創建
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("正在寫入.....");
bw.write(html);
bw.close();
System.out.println("錄入完畢");
} catch (Exception e) {
e.getStackTrace();
}
}
}
使用注意:
1.圖中紅色標記為設定目標網站路徑.
圖片: 1
2.設定網頁源代碼存放目錄和檔案創建
歡迎各位發表評論和問題,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/235471.html
標籤:java
