案例2:從網上獲取《三國演義》全文
需求說明
搭建開發環境,實現《三國演義》全文保存在本地
步驟分析
- 訪問網址:http://www.shicimingju.com/book/sanguoyanyi.html
- 分析網站URL、文檔內容特徵
- 獲取網頁內容
- 拆分出需求內容
- 保存在本地 D:\三國演義.txt
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NovelDemo {
/**
* 1、根據小說存放位置創建file對象
* 2、根據網頁結構編寫正則,創建pattern對象
* 3、編寫循環,創建向所有小說章節頁面發起網絡請求的url對象
* 4、網絡流BufferReader
* 5、創建輸入流
* 6、循環讀取請求得到的內容,使用正則匹配其中的內容
* 7、將讀取到的內容寫入本地文件,知道循環結束
* 8、注意代碼中的異常處理
*/
public static void main(String[] args) {
// 1、根據小說存放位置創建file對象
File file = new File("D:\\三國演義.txt");
if(!file.exists()){ //文件不存在則創建該文件
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 2、根據網頁結構編寫正則,創建pattern對象
String regex_content = "<p.*?>(.*?)</p>";
String regex_title = "<h1>(.*?)</h1>";
Pattern p_content = Pattern.compile(regex_content);
Pattern p_title = Pattern.compile(regex_title);
Matcher m_content;
Matcher m_title;
// 3、編寫循環,創建向所有小說章節頁面發起網絡請求的url對象
for (int i = 1; i <= 120; i++) {
System.out.println("第" + i + "章開始下載。。。");
try {
// 創建每一個頁面的url對象
URL url = new URL("http://www.shicimingju.com/book/sanguoyanyi/" + i + ".html");
// 創建網絡讀取流
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream(), "utf8"));
// 4、讀取網絡內容網絡流BufferReader
String str = null;
// 5、創建輸入流
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true)));
while ((str = reader.readLine()) != null) {
m_title = p_title.matcher(str.toString());
m_content = p_content.matcher(str.toString());
// 獲取小說標題並寫入本地文件
Boolean isEx = m_title.find();
if (isEx) {
String title = m_title.group();
// 清洗得到的數據
title = title.replace("<h1>", "").replace( "</h1>", "");
System.out.println(title);
writer.write("第" + i + "章:" + title + "\n");
}
while (m_content.find()) {
String content = m_content.group();
// 清洗得到的數據
content = content.replace("<p>", "")
.replace("</p>", "")
.replace(" ", "")
.replace("?", "");
// 把小說內容寫入文件
writer.write(content + "\n");
}
}
System.out.println("第" + i + "章下載完成.........");
writer.write("\n\n");
writer.close();
reader.close();
} catch (Exception e) {
System.out.println("下載失敗");
e.printStackTrace();
}
}
}
}
超全面的測試IT技術課程,0元立即加入學習!有需要的朋友戳:
騰訊課堂測試技術學習地址
歡迎轉載,但未經作者同意請保留此段聲明,並在文章頁面明顯位置給出原文鏈接。