Jsoup是一种爬虫技术,同时它也提供了对网页DOM进行解析的一系列方法,通过类JQuery的语法来操作网页标签,获取节点数据。
它诞生的时间,恰巧是JQuery兴起的那些年,JQuery作为一个被广泛使用的前端框架,后端程序猿其实也不陌生——毕竟大部分后端的管理系统,都会用它。
Jsoup的主要功能
从一个URL,文件或字符串中解析HTML
使用DOM或CSS选择器来查找、取出数据使用DOM或CSS选择器来查找、取出数据
可操作HTML元素、属性、文本可操作HTML元素、属性、文本
其实说白了,主要用作爬虫技术。
引入Maven依赖
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.3</version> </dependency>
jsoup API
6个包提供用于开发jsoup应用程序的类和接口。
org.jsoup
org.jsoup.examples
org.jsoup.helper
org.jsoup.nodes
org.jsoup.parser
org.jsoup.safety
org.jsoup.salect
主要类:
Jsoup 类提供了连接,清理和解析HTML文档的方法
Document 获取HTML文档
Element 获取、操作HTML节点
简单入门
1. 三种加载HTML的方法
//从URL加载HTML Document document = Jsoup.connect("http://www.baidu.com").get(); //获取html中的标题 String title = document.title(); //从字符串加载HTML String html = "<html><head><title>First parse</title></head>" + "<body><p>Parsed HTML into a doc.</p></body></html>"; Document doc = Jsoup.parse(html); title = doc.title(); //从文件加载HTML doc = Jsoup.parse(new File("F:\\jsoup\\html\\index.html"),"utf-8"); title = doc.title();
2. 获取html中的head,body,url等信息
Document document = Jsoup.connect("http://www.baidu.com").get(); String title = document.title(); System.out.println("title :"+title); //获取html中的head System.out.println(document.head()); //获取html中的body //System.out.println(document.body()); //获取HTML页面中的所有链接 Elements links = document.select("a[href]"); for (Element link : links){ System.out.println("link : "+ link.attr("href")); System.out.println("text :"+ link.text()); }
3. 获取URL的元信息
Document document = Jsoup.connect("https://passport.lagou.com").get(); System.out.println(document.head()); //获取URL的元信息 String description = document.select("meta[name=description]").get(0).attr("content"); System.out.println("Meta description : " + description); String keywords = document.select("meta[name=keywords]").first().attr("content"); System.out.println("Meta keyword : " + keywords);
4. 提取并打印表单参数
Document document = Jsoup.parse(new File("F:\\jsoup\\html\\login.html"),"utf-8"); Element loginform = document.getElementById("registerform"); Elements inputElements = loginform.getElementsByTag("input"); for (Element inputElement : inputElements) { String key = inputElement.attr("name"); String value = inputElement.attr("value"); System.out.println("Param name: "+key+" -- Param value: "+value); }
其实除了作为爬虫外,Jsoup也适合作为网络请求的框架使用,替代HttpClient。作为轻量级的网络请求技术,Jsoup写法更加简单,更加轻便。
比如在请求各种JSON数据的时候,就可以使用Jsoup。