使用jsoup解析html。
- maven依赖
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
- Java代码
jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.List;
public class Test {
public static void main(String args[]) {
// 网易新闻
String url = "https://www.163.com/";
Document document = null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
// 文字新闻
Elements texts = document.getElementsByClass("cm_ul_round");
for (Element e : texts) {
Elements tags = e.getElementsByTag("a");
for (Element tag : tags) {
// 标题
String title = tag.getElementsByAttribute("href").text();
// 链接地址,可以根据需求继续解析网址,获取新闻详细信息
String href = tag.attributes().get("href");
// 所属分类
String classification = null;
if (href.contains("?") && href.contains("clickfrom=w_")) {
classification = href.substring(href.lastIndexOf("?") + 1).replace("clickfrom=w_", "");
}
System.out.println(title);
System.out.println(href);
System.out.println(classification);
}
}
// 图片新闻
Elements imgs = document.getElementsByClass("cm_bigimg");
for (Element img : imgs) {
Elements photos = img.getElementsByClass("photo");
for (Element photo : photos) {
// 标题
String title = photo.attributes().get("title");
// 链接地址,可以根据需求继续解析网址,获取新闻详细信息
String href = photo.attributes().get("href");
// 封面图
String imgSrc = null;
List<Node> child = photo.childNodes();
for(Node node : child) {
if (node.hasAttr("data-original")) {
imgSrc = node.attributes().get("data-original");
break;
}
}
// 所属分类
String classification = null;
if (href.contains("?") && href.contains("clickfrom=w_")) {
classification = href.substring(href.lastIndexOf("?") + 1).replace("clickfrom=w_", "");
}
System.out.println(title);
System.out.println(href);
System.out.println(imgSrc);
System.out.println(classification);
}
}
}
}