JAVA應用爬蟲抓取網站網頁內容的辦法。本站提示廣大學習愛好者:(JAVA應用爬蟲抓取網站網頁內容的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是JAVA應用爬蟲抓取網站網頁內容的辦法正文
本文實例講述了JAVA應用爬蟲抓取網站網頁內容的辦法。分享給年夜家供年夜家參考。詳細以下:
比來在用JAVA研討下爬網技巧,呵呵,入了個門,把本身的心得和年夜家分享下
以下供給二種辦法,一種是用apache供給的包.另外一種是用JAVA自帶的.
代碼以下:
// 第一種辦法
//這類辦法是用apache供給的包,簡略便利
//然則要用到以下包:commons-codec-1.4.jar
// commons-httpclient-3.1.jar
// commons-logging-1.0.4.jar
public static String createhttpClient(String url, String param) {
HttpClient client = new HttpClient();
String response = null;
String keyword = null;
PostMethod postMethod = new PostMethod(url);
// try {
// if (param != null)
// keyword = new String(param.getBytes("gb2312"), "ISO-8859-1");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// NameValuePair[] data = { new NameValuePair("keyword", keyword) };
// // 將表單的值放入postMethod中
// postMethod.setRequestBody(data);
// 以上部門是帶參數抓取,我本身把它刊出了.年夜家可以把刊出消失落研討下
try {
int statusCode = client.executeMethod(postMethod);
response = new String(postMethod.getResponseBodyAsString()
.getBytes("ISO-8859-1"), "gb2312");
//這裡要留意下 gb2312要和你抓取網頁的編碼要一樣
String p = response.replaceAll("//&[a-zA-Z]{1,10};", "")
.replaceAll("<[^>]*>", "");//去失落網頁中帶有html說話的標簽
System.out.println(p);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// 第二種辦法
// 這類辦法是JAVA自帶的URL來抓取網站內容
public String getPageContent(String strUrl, String strPostRequest,
int maxLength) {
// 讀取成果網頁
StringBuffer buffer = new StringBuffer();
System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
System.setProperty("sun.net.client.defaultReadTimeout", "5000");
try {
URL newUrl = new URL(strUrl);
HttpURLConnection hConnect = (HttpURLConnection) newUrl
.openConnection();
// POST方法的額定數據
if (strPostRequest.length() > 0) {
hConnect.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(hConnect
.getOutputStream());
out.write(strPostRequest);
out.flush();
out.close();
}
// 讀取內容
BufferedReader rd = new BufferedReader(new InputStreamReader(
hConnect.getInputStream()));
int ch;
for (int length = 0; (ch = rd.read()) > -1
&& (maxLength <= 0 || length < maxLength); length++)
buffer.append((char) ch);
String s = buffer.toString();
s.replaceAll("//&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");
System.out.println(s);
rd.close();
hConnect.disconnect();
return buffer.toString().trim();
} catch (Exception e) {
// return "毛病:讀取網頁掉敗!";
//
return null;
}
}
然後寫個測試類:
public static void main(String[] args) {
String url = "http://www.jb51.net";
String keyword = "";
createhttpClient p = new createhttpClient();
String response = p.createhttpClient(url, keyword);
// 第一種辦法
// p.getPageContent(url, "post", 100500);//第二種辦法
}
呵呵,看看掌握台吧,是否是把網頁的內容獲得了
願望本文所述對年夜家的java法式設計有所贊助。