爬蟲
通常搜索引擎處理的對象是互聯網網頁。首先面臨的問題是:如何能夠設計出高效的下載系統,以將如此海量的網頁數據傳送到本地,在本地形成互聯網網頁的鏡像備份。網絡爬蟲即起此作用,它是搜索引擎系統中很關鍵也很基礎的構件。
爬蟲:實際上就是通過相應的技術,抓取頁面上特定的信息。
網絡爬蟲
當"蜘蛛"程序出現時,現代意義上的搜索引擎才初露端倪。它實際上是一種電腦"機器人"(Computer Robot),電腦"機器人"是指某個能以人類無法達到的速度不間斷地執行某項任務的軟件程序。由于專門用于檢索信息的"機器人"程序就象蜘蛛一樣在網絡間爬來爬去,反反復復,不知疲倦。所以,搜索引擎的"機器人"程序就被稱為"蜘蛛"程序。
這種程序實際是利用html文檔之間的鏈接關系,在Web上一個網頁一個網頁的爬取(crawl),將這些網頁抓到系統來進行分析,并放入數據庫中。第一個開發出"蜘蛛"程序的是Matthew Gray,他于1993年開發了World Wide Web Wanderer,它最初建立時是為了統計互聯網上的服務器數量,到后來發展到能夠捕獲網址。現代搜索引擎的思路就來源于Wanderer,后來很多人在此基礎上對蜘蛛程序進行了改進。
我們聽得多的爬蟲可能是python爬蟲,因為以前沒有接觸過這門語言所以感覺爬蟲是一門神秘的技術。今天看了一篇博客介紹的是利用Jsoup包也可以簡便的進行爬蟲開發,令我注意的是這是java的包,于是就有了想自己也做一個爬蟲程序。這也就有了我今天的文章,這也是從小白到大白的一個過程,因為以前沒有寫過類似的,所以還是有點小成就感。閑話就說到這直接上代碼。
其實爬蟲很簡單,首先新建一個java工程。
這是將抓取出來的信息保存到本地,提高效率
/**
*
* @Title: saveHtml
* @Description: 將抓取過來的數據保存到本地或者json文件
* @param 參數
* @return void 返回類型
* @author liangchu
* @date 2017-12-28 下午12:23:05
* @throws
*/
public static void saveHtml(String url) {
try {
// 這是將首頁的信息存入到一個html文件中 為了后面分析html文件里面的信息做鋪墊
File dest = new File("src/temp/reptile.html");
// 接收字節輸入流
InputStream is;
// 字節輸出流
FileOutputStream fos = new FileOutputStream(dest);
URL temp = new URL(url);
// 這個地方需要加入頭部 避免大部分網站拒絕訪問
// 這個地方是容易忽略的地方所以要注意
URLConnection uc = temp.openConnection();
// 因為現在很大一部分網站都加入了反爬蟲機制 這里加入這個頭信息
uc.addRequestProperty(
"User-Agent",
"Mozilla/5.0 "
+ "(iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) "
+ "AppleWebKit/533.17.9"
+ " (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5");
is = temp.openStream();
// 為字節輸入流加入緩沖
BufferedInputStream bis = new BufferedInputStream(is);
// 為字節輸出流加入緩沖
BufferedOutputStream bos = new BufferedOutputStream(fos);
int length;
byte[] bytes = new byte[1024 * 20];
while ((length = bis.read(bytes, 0, bytes.length)) != -1) {
fos.write(bytes, 0, length);
}
bos.close();
fos.close();
bis.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
分析本地的文件信息并將有用的信息提取出來 這一部分是比較耗時的
/*
* 解析本地的html文件獲取對應的數據
*/
public static void getLocalHtml(String path) {
// 讀取本地的html文件
File file = new File(path);
// 獲取這個路徑下的所有html文件
File[] files = file.listFiles();
List<New> news = new ArrayList<New>();
HttpServletResponse response = null;
HttpServletRequest request = null;
int tmp=1;
// 循環解析所有的html文件
try {
for (int i = 0; i < files.length; i++) {
// 首先先判斷是不是文件
if (files[i].isFile()) {
// 獲取文件名
String filename = files[i].getName();
// 開始解析文件
Document doc = Jsoup.parse(files[i], "UTF-8");
// 獲取所有內容 獲取新聞內容
Elements contents = doc.getElementsByClass("ConsTi");
for (Element element : contents) {
Elements e1 = element.getElementsByTag("a");
for (Element element2 : e1) {
// System.out.print(element2.attr("href"));
// 根據href獲取新聞的詳情信息
String newText = desGetUrl(element2.attr("href"));
// 獲取新聞的標題
String newTitle = element2.text();
exportFile(newTitle, newText);
System.out.println("抓取成功。。。"+(tmp));
tmp++;
}
}
}
}
//excelExport(news, response, request);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
根據url的信息獲取這個url下的新聞詳情信息
/**
*
* @Title: desGetUrl
* @Description: 根據url獲取連接地址的詳情信息
* @param @param url 參數
* @return void 返回類型
* @author liangchu
* @date 2017-12-28 下午1:57:45
* @throws
*/
public static String desGetUrl(String url) {
String newText="";
try {
Document doc = Jsoup
.connect(url)
.userAgent(
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
.get();
// System.out.println(doc);
// 得到html下的所有東西
//Element content = doc.getElementById("article");
Elements contents = doc.getElementsByClass("article");
if(contents != null && contents.size() >0){
Element content = contents.get(0);
newText = content.text();
}
//System.out.println(content);
//return newText;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newText;
}
將新聞信息寫入文件中
/*
* 將新聞標題和內容寫入文件
*/
public static void exportFile(String title,String content){
try {
File file = new File("F:/replite/xinwen.txt");
if (!file.getParentFile().exists()) {//判斷路徑是否存在,如果不存在,則創建上一級目錄文件夾
file.getParentFile().mkdirs();
}
FileWriter fileWriter=new FileWriter(file, true);
fileWriter.write(title+"----------");
fileWriter.write(content+"\r\n");
fileWriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
主函數
public static void main(String[] args) {
String url = "http://news.sina.com.cn/hotnews/?q_kkhha";
// 解析本地html文件
getLocalHtml("src/temp");
}
總結
剛開始沒有做過之前覺得爬蟲很神秘,自己真正做一遍之后發現其實也不過如此,其實很多東西都是一樣,我們不要被眼前的困難所迷惑。當勇敢邁出這一步后,就會發現其實自己也可以這樣。