在这个小程序里边,首先是使用一个爬虫,获取网页的出链网址,然后在对获取的所有网页进行执行PageRank算法。
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class GetWebStructure {
public String StartAddress;
public int times;
public ArrayList<WebNodeWithLink> partOfWebStructure=new ArrayList<WebNodeWithLink>();
public ArrayList<WebNode> webStructure=new ArrayList<WebNode>();
public ArrayList<WebsiteToNumber> Mapping=new ArrayList<WebsiteToNumber>();//这个结果用于存储web站点和列号之间的关系
public GetWebStructure(String StartAddress,int times){
this.StartAddress=StartAddress;
this.times=times;
}
public void run() {
String sourcePage=StartAddress;
WebNodeWithLink tmpOfWebNodeWithLink=new WebNodeWithLink(sourcePage,null);
partOfWebStructure.add(tmpOfWebNodeWithLink);
do{
//System.out.println("正在处理partOfWebStructuresize中的新元素");
int count=0;
int thisWebNumber=-1;
//查看当前节点是否已经被存储
for(int n=0;n<Mapping.size();n++)
if(Mapping.get(n).website.equals(partOfWebStructure.get(0).sourcePage)) {
count++;
thisWebNumber=Mapping.get(n).number;
}
//如果已经被存储,则不重新采集它的子节点,否则进入采集器陷阱
if(count==0) {
//当webStructure的大小超过预定times时,不再对partOfWebStructure进行追加
//因为这时候partOfWebStructure中包含的节点已经足以为webStructure中的节点添加子节点
//也不再对webStructure和Mapping进行追加,因为追加后的新节点ID作为times个节点的子节点没有意义
//所以只有partOfWebStructure中的节点在Mapping中已经存在,才会将其标记为times个节点中某个节点的子节点
if(webStructure.size()<times){
//为partOfWebStructure中当前元素获取出链节点
try{
partOfWebStructure.get(0).setTargetPage();//在使用这个记录时才设置它的链出网址和出度
}catch (Exception e){
partOfWebStructure.remove(0);
continue;//出错则进行下一轮do while循环
}
//将获得的出链节点添加到partOfWebStructure中
for(int t=0;t<partOfWebStructure.get(0).outDegree;t++){
sourcePage=partOfWebStructure.get(0).targetPage.get(t);
tmpOfWebNodeWithLink=new WebNodeWithLink(sourcePage,partOfWebStructure.get(0).sourcePage);
//必须被添加到partOfWebStructure,否则当前的子节点将没有机会被添加到它的父节点
//带来了采集器陷阱
partOfWebStructure.add(tmpOfWebNodeWithLink);
}
//将使用过的网址信息映射为数字放置在Mapping中
WebsiteToNumber tmpOfWebsiteToNumber=new WebsiteToNumber();
tmpOfWebsiteToNumber.website=partOfWebStructure.get(0).sourcePage;
thisWebNumber=Mapping.size();
tmpOfWebsiteToNumber.number=thisWebNumber;
Mapping.add(tmpOfWebsiteToNumber);
//将使用过的元素储存在webStructure中,但是这里的使用过的元素并不完整,将在每次向Mapping中添加 使用过的元素的子元素时补充targetPage值
WebNo