dom4j 解析html,【网络爬虫】【java】微博爬虫(四):数据处理——jsoup工具解析html、dom4j读写xml......

之前提到过,对于简单的网页结构解析,可以直接通过观察法、手工写正则解析,可以做出来,比如网易微博。但是对于结构稍微复杂点的,比如新浪微博,如果还用正则,用眼睛一个个去找,未免太麻烦了。

本文介绍两个工具包:解析html, xml的jsoup,和读写xml的dom4j。

工具包jsoup是解析html、xml的利器,利用jsoup可以快速读取html等规范文档格式的节点数据,比正则解析省事多了,而且自己写正则容易考虑不周导致潜在bug,也很容易出错。

同时我们提取出来的微博数据直接存在txt文档里显得结构层次不太清晰,也可以以xml的形式输出,自定义节点,当然首先是得对xml格式有所了解,写xml文件有个工具包dom4j。

下面仅仅给出这两个工具包在这个微博爬虫项目中使用的例子,其实这两个强大的工具包还有其他很多的用法,更多的应用详见官方说明文档。

一、jsoup解析HTML

Jsoup是一个基于java的html解析器,可直接解析某个URL地址、HTML文本内容,其提供的API可以通过DOM, CSS,类jQuery的操作方法读取和操纵数据。

Jsoup主要功能:

1.从一个url、文件或字符串解析html。

2.使用DOM或CSS选择器查找、取出数据。

3.可以操作HTML的元素、属性、文本。

当然jsoup比其他解析器更有优势的地方就是它的选择器功能,很多解析只要一行代码就搞定,而用其他工具包至少都要写很多行。选择器操作比如doc.select(“a[herf]”);选择器select可以选择你想要的任何元素。

在本项目中的代码:

publicString parse(String html) {

String s = '';

Document doc = Jsoup.parse(html);

Elements userNames = doc.select('dt[class].face > a');

Elements userids = doc.select('span > a[action-data]');

Elements dates = doc.select('a[date]');

Elements tweetids = doc.select('dl[mid]');

Elements tweets = doc.select('p > em');

Elements forwardNums = doc.select('a:contains(转发)');

Elements commentNums = doc.select('a:contains(评论)');

for(Element userName : userNames) {

String attr = userName.attr('title');

s += ''+ attr +' ';

}

for(Element userid : userids) {

String attr = userid.attr('action-data');

attr = attr.substring(attr.indexOf('uid='));

Pattern p = Pattern.compile('[0-9]+');

Matcher m = p.matcher(attr);

if(m.find()) {

attr = m.group();

}

s += ''+ attr +' ';

}

for(Element date : dates) {

String attr = date.text();

s += ''+ attr +' ';

}

for(Element tweetid : tweetids) {

String attr = tweetid.attr('mid');

s += ''+ attr +' ';

}

for(Element tweet : tweets) {

String attr = tweet.text();

s += ''+ attr +' ';

}

for(Element forwardNum : forwardNums) {

String attr = forwardNum.text();

if(attr.equals('转发')) {

attr = '0';

}

else{

if(!attr.contains('转发(')) {

attr = '0';

}

else{

attr = attr.substring(attr.indexOf('转发(')+3, attr.indexOf(')'));

}

}

System.out.println(attr);

s += ''+ attr +' ';

}

for(Element commentNum : commentNums) {

String attr = commentNum.text();

if(attr.equals('评论')) {

attr = '0';

}

else{

if(!attr.contains('评论(')) {

attr = '0';

}

else{

attr = attr.substring(attr.indexOf('评论(')+3, attr.indexOf(''));

}

}

System.out.println(attr);

s += ''+ attr +' ';

}

//System.out.println(s);

returns;

}

public String parse(String html) { String s = ''; Document doc = Jsoup.parse(html); Elements userNames = doc.select('dt[class].face > a'); Elements userids = doc.select('span > a[action-data]'); Elements dates = doc.select('a[date]'); Elements tweetids = doc.select('dl[mid]'); Elements tweets = doc.select('p > em'); Elements forwardNums = doc.select('a:contains(转发)'); Elements commentNums = doc.select('a:contains(评论)'); for(Element userName : userNames) { String attr = userName.attr('title'); s += '' + attr + ''; } for(Element userid : userids) { String attr = userid.attr('action-data'); attr = attr.substring(attr.indexOf('uid=')); Pattern p = Pattern.compile('[0-9]+'); Matcher m = p.matcher(attr); if(m.find()) { attr = m.group(); } s += '' + attr + ''; } for(Element date : dates) { String attr = date.text(); s += '' + attr + ''; } for(Element tweetid : tweetids) { String attr = tweetid.attr('mid'); s += '' + attr + ''; } for(Element tweet : tweets) { String attr = tweet.text(); s += '' + attr + ''; } for(Element forwardNum : forwardNums) { String attr = forwardNum.text(); if(attr.equals('转发')) { attr = '0'; } else { if(!attr.contains('转发(')) { attr = '0'; } else { attr = attr.substring(attr.indexOf('转发(')+3, attr.indexOf(')')); } } System.out.println(attr); s += '' + attr + ''; } for(Element commentNum : commentNums) { String attr = commentNum.text(); if(attr.equals('评论')) { attr = '0'; } else { if(!attr.contains('评论(')) { attr = '0'; } else { attr = attr.substring(attr.indexOf('评论(')+3, attr.indexOf('')); } } System.out.println(attr); s += '' + attr + ''; } //System.out.println(s); return s; }

二、dom4j写出微博数据到xml

在本项目中的代码:

publicvoidwriteVector2xml(Vectorvector, String saveXMLPath)throwsIOException {

intvectorSize = vector.size();

String oneIniTweet;

OutputFormat format = OutputFormat.createPrettyPrint();

format.setEncoding('GB2312');//xml被识别格式仅为gb2312,默认utf8不被识别

File f = newFile(saveXMLPath);

f.createNewFile(); //先建立一个空xml文件

FileWriter fw = newFileWriter(f);

org.dom4j.Document document = DocumentHelper.createDocument(); //建document对象实例

org.dom4j.Element rootElement = document.addElement('tweets');//节点增加方法

rootElement.addAttribute('totalNumber', String.valueOf(vectorSize));//设置属性

for(intj=0; j

oneIniTweet = vector.get(j);

String userName = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf(' '));

String userId = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf(' '));

String prettyTime = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf(' '));

String tweetSentence = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf(' '));

org.dom4j.Element tweetElement = rootElement.addElement('tweet');

tweetElement.addAttribute('userName', userName);

tweetElement.addAttribute('userId', userId);

tweetElement.addAttribute('prettyTime', prettyTime);

tweetElement.setText(tweetSentence); // 设置节点文本内容

}

XMLWriter xw = newXMLWriter(fw, format);

xw.write(document);

xw.close();

}

public void writeVector2xml(Vectorvector, String saveXMLPath) throws IOException { int vectorSize = vector.size(); String oneIniTweet; OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding('GB2312'); //xml被识别格式仅为gb2312,默认utf8不被识别 File f = new File(saveXMLPath); f.createNewFile(); //先建立一个空xml文件 FileWriter fw = new FileWriter(f); org.dom4j.Document document = DocumentHelper.createDocument(); //建document对象实例 org.dom4j.Element rootElement = document.addElement('tweets'); //节点增加方法 rootElement.addAttribute('totalNumber', String.valueOf(vectorSize)); //设置属性 for(int j=0; j'), oneIniTweet.indexOf(' ')); String userId = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf('')); String prettyTime = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf('')); String tweetSentence = oneIniTweet.substring(oneIniTweet.indexOf(''), oneIniTweet.indexOf('')); org.dom4j.Element tweetElement = rootElement.addElement('tweet'); tweetElement.addAttribute('userName', userName); tweetElement.addAttribute('userId', userId); tweetElement.addAttribute('prettyTime', prettyTime); tweetElement.setText(tweetSentence); // 设置节点文本内容 } XMLWriter xw = new XMLWriter(fw, format); xw.write(document); xw.close(); }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Jsoup是一个用于解析HTML文档的开源库。通过使用Jsoup,您可以轻松地从HTML文档中提取数据或进行数据操作。以下是使用Java Jsoup解析HTML的基本步骤: 1. 下载Jsoup库:您可以从Jsoup的官方网站(https://jsoup.org/)下载Jsoup库的最新版本。 2. 导入Jsoup库:将下载的Jsoup库的JAR文件导入到您的Java项目中。 3. 创建连接:使用Jsoup.connect()方法创建一个Connection对象,将HTML文档的URL作为参数传递给该方法。 4. 获取Document对象:使用Connection对象的get()方法获取一个Document对象,该对象表示整个HTML文档。 5. 使用选择器进行数据提取:使用Jsoup的选择器语法,您可以根据HTML元素的标签、类名、ID等属性来选择和提取数据。 以下是一个基本的Java Jsoup解析HTML的示例代码: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class HtmlParser { public static void main(String[] args) { try { // 创建连接 Connection connection = Jsoup.connect("http://example.com"); // 获取Document对象 Document document = connection.get(); // 使用选择器提取数据 Elements links = document.select("a[href]"); for (Element link : links) { System.out.println("Link: " + link.attr("href")); System.out.println("Text: " + link.text()); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码将从"http://example.com"网页中提取所有链接的URL和文本,并打印出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值