java jsoup解析html标签_JSoup——用Java解析html网页内容

public static HashMapgetDetails(String html)

{

HashMap details = new HashMap();//解析开始

Document doc =Jsoup.parse(html);//获取形如

something
的第一个div元素,class^=result_info表示class以result_info开头,^是正则表达式的开始

Element divAll = doc.select("div[class^=result_info]").first();//System.out.println(divAll.text());

Element head = divAll.select("h3").first();//获取div中的h3标签

String tvname = head.select("a").attr("title").trim();//获取h3标签中a标签的title属性值

String year = "";if (head.select("em").size() > 0)//假如h3标签中存在多个标签

{

year= head.select("em").first().text().trim();//只要第一个首尾之间的文本

}

String score= "";

Element scoreSection= divAll.select("p").first();if (scoreSection != null)

{

Elements es= scoreSection.select("span");//选择span元素

int size =es.size();for (int i = 0; i < size; i++)

{

Element e=es.get(i);

String content=e.text().trim();

content= content.replace("\u00A0", "");//替换 为空格

score +=content;

}

}

HashMap lstOtherInfo = new HashMap();

Elements otherSections= divAll.select("div[class^=result_info_cont]");//获取满足class以result_info_cont开头的所有div元素

int size = otherSections.size();//获取满足条件的div元素的总数是多少

int infoCount = 0;for (int i = 0; i < size && infoCount < 3; i++)

{

String value= "";

Element item= otherSections.get(i);//获取第i个元素

boolean keyflag = true;

String key= "";for (int index = 0; index < item.children().size(); index++)//Element.children()用于获取元素的直接子元素

{

Element e= item.child(index);//获取第index个子元素

if(keyflag)

{

key=e.text().trim();if (key == "简介")break;

keyflag= false;

}else{if (e.children().size() > 0)

{for (int b = 0; b < e.children().size(); b++)

{

value+= e.child(b).text().trim() + ",";

}

}else{

String contents=e.text().trim();

value+= contents + ",";

}

}

}

value= value.replaceAll("[" + "," + "]$", "");

lstOtherInfo.put(key, value);

infoCount++;

}

details.put("tv", tvname);

details.put("year", year);

details.put("score", score);

details.put("otherInfo", lstOtherInfo);returndetails;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值