java抓取网页内容(JAVA的API可以顺利的抓取网络上的大部分指定的网页内容)
优采云 发布时间: 2022-03-29 11:21java抓取网页内容(JAVA的API可以顺利的抓取网络上的大部分指定的网页内容)
通过JAVA API,可以成功抓取网络上大部分的指定网页内容。下面就和大家分享一下对这种方法的理解和体会。最简单的抓取方法是:
URLurl=newURL(myurl);BufferedReaderbr=newBufferedReader(newInputStreamReader(url.openStream()));Strings="";StringBuffersb=newStringBuffer("");while((s=br.readLine())!=null){ i++;sb.append(s+"\r\n");}
URL url = new URL(myurl);
BufferedReader br = new BufferedReader(newInputStreamReader(url.openStream()));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
i++;
sb.append(s+"\r\n");
}
这种方法爬一般的网页应该是没问题的,但是当一些网页中有嵌套的重定向连接时,会报Server redirected too many times之类的错误,这是因为这个网页里面有一些代码是转到其他网页,太多的循环导致程序错误。如果只想爬取这个URL中的网页内容,不想跳转到其他网页,可以使用下面的代码。
URLurlmy=newURL(myurl);HttpURLConnectioncon=(HttpURLConnection)urlmy.openConnection();con.setFollowRedirects(true);con.setInstanceFollowRedirects(false);con.connect();BufferedReaderbr=newBufferedReader(newInputStreamReader(con.getInputStream(), "UTF-8"));Strings="";StringBuffersb=newStringBuffer("");while((s=br.readLine())!=null){sb.append(s+"\r\n"); }
URL urlmy = new URL(myurl);
HttpURLConnection con = (HttpURLConnection) urlmy.openConnection();
con.setFollowRedirects(true);
con.setInstanceFollowRedirects(false);
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
sb.append(s+"\r\n");
}
这样,在爬取的时候,程序就不会跳转到其他页面去爬取其他内容,就达到了我们的目的。
如果我们在 Intranet 中,我们还需要为其添加代理。Java 提供对具有特殊系统属性的代理服务器的支持,只要在上述程序中添加以下程序即可。
Java 代码
System.getProperties().setProperty("http.proxyHost",proxyName);System.getProperties().setProperty("http.proxyPort",port);
System.getProperties().setProperty( "http.proxyHost", proxyName );
System.getProperties().setProperty( "http.proxyPort", port );
这样,您就可以在内网的同时从Internet上抓取您想要的东西。
上面程序捕获的所有内容都存储在sb字符串中,我们可以通过正则表达式进行分析,提取出我们想要的具体内容,为我所用!