java爬虫抓取动态网页(爬虫程序就是自动搜索获取内容的程序,我的需求 )
优采云 发布时间: 2022-02-21 23:29java爬虫抓取动态网页(爬虫程序就是自动搜索获取内容的程序,我的需求
)
几年没写代码了,也不觉得以后会是码农,但是对编程的实用性还是挺感兴趣的。采集每次游泳的链接资源的想法,毕业后就没什么好担心的了。我开始思考了一两个小时,做了一个小爬虫来抓取这些超链接资源。当然,我的功能还是很简单的。这里不想写什么专业的东西,把自己写的原创源码贴出来分享给大家。
爬虫是一种自动搜索和获取内容的程序。我的需求是弄个采集网页内容的小爬虫,也叫网络爬虫,用来采集有用的超链接信息。
网络爬虫的简单原理(据我了解)是从给定的 URL 爬取相应网页的内容。给定的 URL 可以手动分配,也可以由爬虫自己自动解析。通过正则表达式判断需要爬取的网页内容,如何爬取是网页数据流的实现过程。所以小爬虫所涉及的技术非常基础,所以我就分类贴下下一个人的原代码。
一、通过 URL 获取网页内容
public StringBuffer getContext(String URLPath)
{
StringBuffer buffer= new StringBuffer();
try {
URL url = new URL(URLPath);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line = reader.readLine()) != null)
buffer.append(line + "\n");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
二、解析网页内容
/**
* 解析网页内容,返回所需的信息,可以是String型,此处是因实际需要返回map
* @param htmlDoc 网页内容
*/
public LinkedHashMap urlDetector(String htmlDoc)
{
//key存放超链接显示名,value存放相对地址路径名
LinkedHashMap map = new LinkedHashMap();
final String patternString = "([^\\s]+)>>>");
buf1.append(keyName + "\n");
String BtStr = t.collectBTorOther(uPath, filePath + keyName + ".tmp");
buf1.append(BtStr);
buf1.append("-----------------------------------------------\n");
}
}
<p> /**
* 接上面,特殊处理
* @param uPath
* @param fPath
*/
public String collectBTorOther(String uPath, String fPath)
{
StringBuffer buf = this.getContext(uPath);
this.writeToFile(fPath, buf);
// 解析网页内容,返回需要收集的信息
final String patternBT = "http:[^>\"'