API例子:用Java/JavaScript下載內容提取器

圖片描述

1,引言

本文講解怎樣用Java和JavaScript使用 GooSeeker API 接口下載內容提取器,這是一個示例程序。什麼是內容提取器?爲何用這種方式?源自Python即時網絡爬蟲開源項目:經過生成內容提取器,大幅節省程序員時間。具體請參看《內容提取器的定義》html

2, 用Java下載內容提取器

這是一系列實例程序中的一個,就目前編程語言發展來看,Java實現網頁內容提取並不合適,除了語言不夠靈活便捷之外,整個生態不夠活躍,可選的類庫增加緩慢。另外,要從JavaScript動態網頁中提取內容,Java也很不方便,須要一個JavaScript引擎。用JavaScript下載內容提取器能夠直接跳到第3部分的內容。node

具體實現git

註解:程序員

  • 使用Java類庫 jsoup(1.8.3以上版本),能夠很便利、快速的獲取網頁dom。github

  • 經過GooSeeker API 獲取xslt(參考 1分鐘快速生成用於網頁內容提取的xsltajax

  • 使用Java自帶的類TransformerFactory執行網頁內容轉換編程

源代碼以下:segmentfault

public static void main(String[] args)
{
    InputStream xslt = null;
    try
    {
        String grabUrl = "http://m.58.com/cs/qiuzu/22613961050143x.shtml"; // 抓取網址
        String resultPath = "F:/temp/xslt/result.xml"; // 抓取結果文件的存放路徑
        // 經過GooSeeker API接口得到xslt
        xslt = getGsExtractor();
        // 抓取網頁內容轉換結果文件
        convertXml(grabUrl, xslt, resultPath);
    } catch (Exception e)
    {
        e.printStackTrace();
    } finally
    {
        try
        {
            if (xslt != null)
                xslt.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

`/**`
 `* @description dom轉換`
 `*/`
public static void convertXml(String grabUrl, InputStream xslt, String resultPath) throws Exception
{
    // 這裏的doc對象指的是jsoup裏的Document對象
    org.jsoup.nodes.Document doc = Jsoup.parse(new URL(grabUrl).openStream(), "UTF-8", grabUrl);
    W3CDom w3cDom = new W3CDom();
    // 這裏的w3cDoc對象指的是w3c裏的Document對象
    org.w3c.dom.Document w3cDoc = w3cDom.fromJsoup(doc);
    Source srcSource = new DOMSource(w3cDoc);
    TransformerFactory tFactory =   TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(new StreamSource(xslt));
    transformer.transform(srcSource, new StreamResult(new FileOutputStream(resultPath)));
}

`/**`
 `* @description 獲取API返回結果`
 `*/`
public static InputStream getGsExtractor()
{
    // api接口
    String apiUrl = "http://www.gooseeker.com/api/getextractor";
    // 請求參數
    Map<String,Object> params = new HashMap<String, Object>();
    params.put("key", "xxx");  // Gooseeker會員中心申請的API KEY
    params.put("theme", "xxx");  // 提取器名,就是用MS謀數臺定義的規則名
    params.put("middle", "xxx");  // 規則編號,若是相同規則名下定義了多個規則,需填寫
    params.put("bname", "xxx"); // 整理箱名,若是規則含有多個整理箱,需填寫
    String httpArg = urlparam(params);
    apiUrl = apiUrl + "?" + httpArg;
    InputStream is = null;
    try
    {
        URL url = new URL(apiUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setRequestMethod("GET");
        is = urlCon.getInputStream();
    } catch (ProtocolException e)
    {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return is;
}

`/**`
 `* @description 請求參數`
 `*/`
public static String urlparam(Map<String, Object> data)
{
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, Object> entry : data.entrySet())
    {
        try
        {
            sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue() + "", "UTF-8")).append("&");
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

返回結果以下:
圖片描述api

3, 用JavaScript下載內容提取器

請注意,若是本例的JavaScript代碼是在網頁上運行的,由於跨域問題,是沒法實現非本站網頁內容爬取的。因此,要運行在具備特權的JavaScript引擎上,好比,瀏覽器擴展程序、自研的瀏覽器、本身的程序中含有JavaScript引擎等。跨域

本例爲了實驗方便,仍然放在網頁上運行,爲了繞開跨域問題,是把目標網頁存下來並進行修改,把JavaScript插入進去。這麼多人工操做,僅僅是爲了實驗,正式使用的時候須要考慮別的手段。

具體實現

註解:

  • 引用 jQuery 類庫 (jQuery-1.9.0 以上)

  • 爲了解決跨域問題,把目標網頁預先保存到硬盤上

  • 在目標網頁中插入JavaScript代碼

  • 使用GooSeeker API,把內容提取器下載下來,內容提取器是一個xslt程序,下例使用了jQuery的ajax方法從api得到xslt

  • 用xslt處理器做內容提取

下面是源代碼:

// 目標網頁網址爲http://m.58.com/cs/qiuzu/22613961050143x.shtml,預先保存成本地html文件,並插入下述代碼
$(document).ready(function(){
    $.ajax({
        type: "get", 
        url: "http://www.gooseeker.com/api/getextractor?key=申請的appKey&theme=規則主題名", 
        dataType: "xml", 
        success: function(xslt)
            {
            var result = convertXml(xslt, window.document);
            alert("result:" + result);
        } 
    });  
});

/* 用xslt將dom轉換爲xml對象 */
function convertXml(xslt, dom)
{
    // 定義XSLTProcessor對象
    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xslt);
    // transformToDocument方式
    var result = xsltProcessor.transformToDocument(dom);
    return result;
}

返回結果截圖以下
圖片描述

4,展望

一樣能夠用Python來獲取指定網頁內容,感受Python的語法更加簡潔,後續增長Python語言的示例,有興趣的小夥伴能夠加入一塊兒研究。

5,相關文檔

1, Python即時網絡爬蟲:API說明

6,集搜客GooSeeker開源代碼下載源

1, GooSeeker開源Python網絡爬蟲GitHub源

7,文檔修改歷史

1,2016-06-24:V1.0

相關文章
相關標籤/搜索