Java 爬虫实战二之获取CSDN博主排名

1.需求

根据csdn的博主网址,获取其个人排名信息。然后将信息写入到openTSDB中,【其实底层是写入到HBase数据库中】,进行数据的时序分析。

2.代码

  • CsdnHtml类
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;

public class CsdnHtml extends Html {
public ArrayList getSpecificInfo(String name, String url, String classType, String charset) {
ArrayList arrayList = new ArrayList();

String[] result = new String[4];
Element tempEle = null;
Document document = this.getHtmlTextByPath(name,url,charset);//care! The document is in org.jsoup.nodes
if(document!=null){
Elements eSets = document.getElementsByClass(classType);//care! The Element is in org.jsoup.select.Elements
for(Element eUnit : eSets){// get every Element unit
if(eUnit!=null){//eUnit是标签<div>那层
int i = 0;
for(Element eCell : eUnit.children()) //一个tr的子元素td,td内包含a标签
{//eCell 是标签<dl>那层
result[0]=eCell.children().first().ownText();//<dt>层
tempEle=eCell.child(1);//<dd>层
result[1]=tempEle.ownText();
if(i==0){
result[1]=tempEle.child(0).attr("href");
//result[2] = tempEle.children().attr("title");
result[2] = tempEle.child(0).attr("title").substring(0,2);//[0,2)
}
else
result[2]=tempEle.attr("title");
if(i==3)
result[2] = result[1];
System.out.println(result[0] +"\t"+ result[1] +"\t"+ result[2]);
i++;
}
}
}
}
return arrayList;
}
}

该类中继承的抽象类​​Html​​,以及使用测试主类​​TestCrawler​​在上篇博文《​​Java爬虫实战一之获取全国信息​​》中都有介绍。

针对上述的代码,下面给出csdn官网的部分前端代码,目的是为了更好的使用dom树知识。

<dl>
<dt>等级:</dt>
<dd>
<a href="https://blog.csdn.net/home/help.html#level" title="6级,点击查看等级说明" target="_blank">
<svg class="icon icon-level" aria-hidden="true">
<use xlink:href="#csdnc-bloglevel-6"></use>
</svg>
</a>
</dd>
</dl>
<dl>
<dt>访问:</dt>
<dd title="176646">17万+</dd>
</dl>
<dl>
<dt>积分:</dt>
<dd title="7087">7087</dd>
</dl>
<dl title="4547">
<dt>排名:</dt>
<dd>4547</dd>
</dl>

3.执行结果

Java 爬虫实战二之获取CSDN博主排名_ico

下一步骤就是讲获取到的数据写入到openTSDB中,敬请期待下一篇博客。