当前位置:文档之家› JAVA使用爬虫抓取网站网页内容的方法_java_脚本之家

JAVA使用爬虫抓取网站网页内容的方法_java_脚本之家


9
HttpClient client = new HttpClient();
10
String response = null ;
11
12
String keyword = null ;
13
PostMethod postMethod = new PostMethod(url);
14
// try {
15
16
68 69
.getOutputStream());
70
out.write(strPostRequest);
71
out.flush();
72 73
out.close();
74
}
// 读取内容
BufferedReader rd = new BufferedReader( new InputStreamReader(
56 57
System.setProperty( ".client.defaultReadTimeout" , "5000" );
58
try {
59
URL newUrl = new URL(strUrl);
60 61
HttpURLConnection hConnect = (HttpURLConnection) newUrl
33
.getBytes( "ISO‐8859‐1" ), "gb2312" );
34
//这里要注意下 gb2312要和你抓取网页的编码要一样
35
36
String p = response.replaceAll( "//&[a‐zA‐Z]{1,10};" , "" )
37
.replaceAll( "<[^>]*>" , "" ); //去掉网页中带有html语言的标签
27
28
// 以上部分是带参数抓取,我自己把它注销了.大家可以把注销消掉研究下
29
try {
30
int statusCode = client.executeMethod(postMethod);
31
32
response = new String(postMethod.getResponseBodyAsString()
hConnect.getInputStream()));
int ch;
for ( int length = 0 ; (ch = rd.read()) > ‐ 1
&& (maxLength <= 0 || length < maxLength); length++)
buffer.append(( char ) ch);
38
System.out.println(p);
39
40
} catch (Exception e) {
41
e.printStackTrace();
42
}
43
44
return response;
45
}
46
// 第二种方法
47 48
// 这种方法是JAVA自带的URL来抓取网站内容
49
public String getPageContent(String strUrl, String strPostRequest,
// if (param != null)
17
// keyword = new String(param.getBytes("gb2312"), "ISO‐8859‐1");
18
// } catch (UnsupportedEncodingException e1) {
19
20
// // TODO Auto‐generated catch block
return buffer.toString().trim();
} catch (Exception e) {
// return "错误:读取网页失败!";
//
return null ;
}
}
然后写个测试类:
?
1
public static void main(String[] args) {
2
String url = "" ;
21
// e1.printStackTrace();
22
// }
23
24
// NameValuePair[] data = { new NameValuePair("keyword", keyword) };
25
// // 将表单的值放入postMethod中
26
// postMethod.setRequestBody(data);
3
4
//但是要用到以下包:commons‐codec‐1.4.jar
5
// commons‐httpclient‐3.1.jar
6
// commons‐logging‐1.0.4.jar
7
8
public static String createhttpClient(String url, String param) {
本文实例讲述了JAVA使用爬虫抓取网站网页内容的方法。分享给大家供大家参考。具体如下: 最近在用JAVA研究下爬网技术,呵呵,入了个门,把自己的心得和大家分享下 以下提供二种方法,一种是用apache提供的包.另一种是用JAVA自带的. 代码如下:
?
1
// 第一种方法
2
//这种方法是用apache提供的包,简单方便
50
int maxLength) {
51
52
// 读取结果网页
53
StringBuffer buffer = new StringBuffer();
54
55
ห้องสมุดไป่ตู้ 55
System.setProperty( ".client.defaultConnectTimeout" , "5000" );
}
呵呵,看看控制台吧,是不是把网页的内容获取了
3
4
String keyword = "脚本之家" ;
5
createhttpClient p = new createhttpClient();
6
String response = p.createhttpClient(url, keyword);
7
8
// 第一种方法
// p.getPageContent(url, "post", 100500);//第二种方法
String s = buffer.toString();
s.replaceAll( "//&[a‐zA‐Z]{1,10};" , "" ).replaceAll( "<[^>]*>" , ""
System.out.println(s);
rd.close();
hConnect.disconnect();
62
.openConnection();
63
// POST方式的额外数据
64 65
if (strPostRequest.length() > 0 ) {
66
hConnect.setDoOutput( true );
67
OutputStreamWriter out = new OutputStreamWriter(hConnect
相关主题