日期:2014-05-17 浏览次数:20672 次
java采集数据,获取了 html整个文本之后。
该考虑的是如何过滤掉html标签, 得到自己所需要的重要数据了。
实现方法有多种办法,第一:用正则,第二:用第三方jar包,其实本质也是封装了正则表达式
今天就以 Jsoup 第三方jar包来讲解。
jsoup详细资料:http://blog.csdn.net/yjflinchong/article/details/7743995
转载注明出处:http://blog.csdn.net/column/details/threadgrab.html
现在贴上一个网页过滤的方法实例
//门票浏览 url参数 http://www.lvmama.com/dest/lantiancheng public static DataBean getWebData1(String url){ DataBean data = null; try { Document docdata = Jsoup.connect(url).timeout(20000).get(); String id = ".quick-menu .last a"; String city = ".proDetail a"; String title = ".proDetail h1"; String content = "#Introduction"; Elements ele = docdata.select(city); city = (ele.text()); ele = docdata.select(title); title = (ele.text()).replace("<", "").replace(">", "").replace("\\/", ""); ele = docdata.select(content); content = (ele.text()); ele = docdata.select(id); String[] idary = ele.attr("href").split("\\/"); id = idary[idary.length-1]; String type = "景点门票"; List<String> images = new ArrayList<String>(); data = new DataBean(id,title,url,content,type,city,images); Dom4jUtil.createFile("data/["+type+"]"+title+".xml", Dom4jUtil.createDocument(data)); type = "景点评论"; content = ".userComments dl dd:eq(3)"; ele = docdata.select(content); content = ""; int i = 1; for (Element el : ele) { content += ("|第"+i+":"+el.text()); i++; } data = new DataBean(id,title,url,content,type,city,images); //用xml存储数据 Dom4jUtil.createFile("data/["+type+"]"+title+".xml", Dom4jUtil.createDocument(data)); } catch (Exception e) { e.printStackTrace(); } return data; }
整个过程分为几部
1、 获取页面的节点对象
Document docdata = Jsoup.connect(url).timeout(20000).get();
2、创建选择器,选择页面节点对象的 text 或 html 。 选择方式跟jquery非常类似。
例如:
String title = ".proDetail h1";
ele = docdata.select(title);
这个就是用来选择 class = proDetail 下 h1 标签的对象。通过 ele.text() 就得到了标签中的文本。
Document docdata = Jsoup.connect(url).timeout(20000).get(); String id = ".quick-menu .last a"; String city = ".proDetail a"; String title = ".proDetail h1"; String content = "#Introduction"; Elements ele = docdata.select(city); city = (ele.text()); ele = docdata.select(title); title = (ele.text()).replace("<", "").replace(">", "").replace("\\/", ""); ele = docdata.select(content); content = (ele.text()); ele = docdata.select(id); String[] idary = ele.attr("href").split("\\/"); id = idary[idary.length-1];
String type = "景点门票"; List<String> images = new ArrayList<String>(); data = new DataBean(id,title,url,content,type,city,images); Dom4jUtil.createFile("data/["+type+"]"+title+".xml", Dom4jUtil.createDocument(data));
转载注明出处:http://blog.csdn.net/yjflinchong
java采集数据过滤html标签,获取指定数据,就搞定了