Java爬蟲之利用Jsoup自制簡單的搜索引擎

  Jsoup 是一款Java 的HTML解析器,可直接解析某個URL地址、HTML文本內容。它提供了一套很是省力的API,可經過DOM,CSS以及相似於jQuery的操做方法來取出和操做數據。Jsoup的官方網址爲: https://jsoup.org/, 其API使用手冊網址爲:https://jsoup.org/apidocs/ove... .
  本次分享將實現的功能爲:利用Jsoup爬取某個搜索詞語(暫僅限英文)的百度百科的介紹部分,具體的功能介紹能夠參考博客:Python爬蟲——自制簡單的搜索引擎。在上篇爬蟲中咱們用Python進行爬取,此次,咱們將用Java來作爬蟲,你沒看錯,就是Java.
  在Eclipse中加入Jsoup包,下載網址爲:https://jsoup.org/download .
  爬蟲的具體代碼以下:html

package baiduScrape;

/* 
 * 本爬蟲主要利用Java的Jsoup包進行網絡爬取
 * 本爬蟲的功能: 爬取百度百科的開頭介紹部分
 * 使用方法: 輸入關鍵字(目前只支持英文)便可
 */

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.net.*;
import java.io.*;
import java.util.Scanner;

public class BaiduScrape {
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String baseUrl = "https://baike.baidu.com/item/";
        String url = "";
        
        // 若是輸入文字不是"exit",則爬取其百度百科的介紹部分,不然退出該程序
        while(true) {
            System.out.println("Enter the word(Enter 'exit' to exit):");
            url = input.nextLine();
            if(url.equals("exit")) {
                System.out.println("The program is over.");
                break;
            }
            String introduction = getContent(baseUrl+url);
            System.out.println(introduction+'\n');
        }
    }
    
    // getContent()函數主要實現爬取輸入文字的百度百科的介紹部分
    public static String getContent(String url){
        // 利用URL解析網址
        URL urlObj = null;
        try{
            urlObj = new URL(url);
            
        }
        catch(MalformedURLException e){
            System.out.println("The url was malformed!");
            return "";
        }
        
        // URL鏈接
        URLConnection urlCon = null;
        try{
            urlCon = urlObj.openConnection(); // 打開URL鏈接
            // 將HTML內容解析成UTF-8格式
            Document doc = Jsoup.parse(urlCon.getInputStream(), "utf-8", url);
            // 刷選須要的網頁內容
            String contentText = doc.select("div.lemma-summary").first().text();
            // 利用正則表達式去掉字符串中的"[數字]"
            contentText = contentText.replaceAll("\\[\\d+\\]", "");
            return contentText;
        }catch(IOException e){
            System.out.println("There was an error connecting to the URL");
            return "";
        }
        
    }
}

在上述代碼中,url爲輸入詞條(暫時僅限於英文),進入while循環可一直搜索,當輸入爲’exit’時退出。contentText爲該詞條的百度百科簡介的網頁形式,經過正則表達式將其中的文字提取出來。代碼雖然簡潔,可是功能仍是蠻強大的,充分說明Java也是能夠作爬蟲的。
  接下來是愉快的測試時間:java

運行結果

  本次分享到此結束,接下來也會持續更新Jsoup方面的相關知識,歡迎你們交流~~node

相關文章
相關標籤/搜索