1. 程式人生 > >網頁資料抓取之讀取網頁資料

網頁資料抓取之讀取網頁資料

最近專案中需要用到各大網站的資料,這裡沒用爬蟲,用純java程式碼,無任何外掛,抓取一些自己需要的資料!
後續會記錄主要的幾個網站資料抓取,主要針對帶單個搜尋框的網站!

下面是一個公用的讀取網頁資料操作類:

package com.atman.baiye.store.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * remark
 * 
[email protected]
* 2017年1月18日下午4:02:09 */ public class WebHttpClient { /** * url-web地址 * keyWord-搜尋關鍵字 * isEncoder-是否需要對關鍵字進行轉碼 * charset-編碼方式,需要時設定 * 2017年1月18日下午4:02:09 */ public static String getBebContentByURL(String url, String keyWord, boolean isEncoder, String charset){ String result = ""; if(!"".equals(keyWord) && isEncoder){ keyWord = URLEncoder.encode(keyWord); } url += keyWord; BufferedReader in = null; try { URL realUrl = new URL(url); // 開啟和URL之間的連線 URLConnection connection = realUrl.openConnection(); // 設定通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的連線 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 InputStreamReader input = new InputStreamReader( connection.getInputStream()); if(!"".equals(charset)){ input = new InputStreamReader( connection.getInputStream(),charset); } in = new BufferedReader(input); String line; while ((line = in.readLine()) != null) { result += line; } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } }