java爬虫抓取网页数据(网络爬虫的实现原理:网络蜘蛛又叫蜘蛛,流程 )
优采云 发布时间: 2021-10-19 08:14java爬虫抓取网页数据(网络爬虫的实现原理:网络蜘蛛又叫蜘蛛,流程
)
网络爬虫的实现原理:
网络爬虫也被称为蜘蛛。过程为:网络蜘蛛通过网页的链接地址搜索网页。从某个页面(通常是首页)开始,阅读网页内容,找到网页中的其他链接。地址,通过这些链接地址找到下一个网页,一直循环下去,直到这个网站的所有网页都被抓取完毕。根据特定的网页规则,在抓取的网页中提取你想要的信息。如果把整个互联网看作一个网站,那么网络蜘蛛就可以利用这个原理抓取互联网上的所有网页。因此,如果要抓取互联网上的数据,不仅需要一个爬虫程序,还需要一个能够接受“爬虫”发回的数据并对数据进行处理和过滤的服务器。爬虫抓取的数据量越大,对服务器的性能要求就越高。.
根据这个原理,编写一个简单的网络爬虫程序。该程序的作用是获取网站发回的数据,并在该过程中提取URL。获取的 URL 存储在文件夹中。如何使用网站获取的URL进一步循环获取数据,提取其他数据。我不打算在这里写。它只是模拟最简单的原理。实际的 网站 爬虫比这里复杂得多。有太多深入的讨论。除了提取URL,我们还可以提取我们想要的各种其他信息。
结构目录:
源代码:
package com.sun.crawl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import sun.jdbc.odbc.JdbcOdbc;
import java.io.IOException;
/**
* 下载此超链接的页面源代码.
*/
public class DownloadPage {
/**
* 根据URL抓取网页内容
*
* @param url
* @return
*/
public static String getContentFormUrlAndDownloadGoalContent(String url) {
/* 实例化一个HttpClient客户端 */
HttpClient client = new DefaultHttpClient();
HttpGet getHttp = new HttpGet(url);
String content = null;
HttpResponse response;
try {
/* 获得信息载体 */
response = client.execute(getHttp);
HttpEntity entity = response.getEntity();
VisitedUrlQueue.addElem(url);
if (entity != null) {
/* 转化为文本信息 */
content = EntityUtils.toString(entity);
/* 判断是否符合下载网页源代码到本地的条件 */
if (FunctionUtils.isCreateFile(url)
&& FunctionUtils.isHasGoalContent(content) != -1) {
/*
//将抓包的数据存到磁盘上(D盘下)
FunctionUtils.createFile(
FunctionUtils.getGoalContent(content), url);*/
FoodMessageBean foodMessageBean = FunctionUtils.CutHtml(FunctionUtils.getGoalContent(content));
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return content;
}
}
package com.sun.crawl;
/**
* Created by lenovo on 2017/8/3.
*/
public class FoodMessageBean {
private String name = "";
private String property = "";
private String content = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "FoodMessageBean{" +
"name='" + name + '\'' +
", property='" + property + '\'' +
", content='" + content + '\'' +
'}';
}
}
<p>package com.sun.crawl;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FunctionUtils {
public static FoodMessageBean CutHtml(String content) {
FoodMessageBean f = new FoodMessageBean();
// 过滤文章内容中的html
String[] split = content.split(":");
String s = split[0].replaceAll("