Java 的HTML解析器- jsoup

導入郵件Maven jar包

    <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
	<dependency>
	    <groupId>org.jsoup</groupId>
	    <artifactId>jsoup</artifactId>
	    <version>1.11.3</version>
	</dependency>

使用 jsoup 提供的 connect(String url) 方法創建一個新的 Connection,並通過 get() 獲取網頁對應的 HTML 文件

Document doc = Jsoup.connect("網頁地址").get();
System.out.println(doc);
//通過這兩行程序便可以在 Eclipse 控制檯輸入該網址對應的 HTML 文件(由於該 HTML 文件的內容過長,,在此我就不展示了)。另外,jsoup 也可以使用 Post() 方法請求網頁內容,使用如下:

//可以看到該網址通過兩種方法都能請求到內容
Document doc = Jsoup.connect("網頁地址").post();
System.out.println(doc);
//另外,在爬取一些網站時,可能需要添加頭信息。添加頭信息可以很好地僞裝我們的爬蟲,使得該爬蟲更像是瀏覽器訪問,從而降低了爬蟲被封的風險。同樣,針對網絡地址爲例,通過抓包獲取 Request Headers,並將這些頭信息添加到程序中,具體程序如下:
Connection connect = Jsoup.connect("網頁地址"); //獲取請求連接
//使用Map集合存儲頭信息
Map<String, String> header = new HashMap<String, String>();
header.put("Host", "www.w3school.com.cn");
header.put("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36");
header.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
header.put("Accept-Language", "zh-cn,zh;q=0.5");
header.put("Accept-Encoding", "gzip, deflate");
header.put("Cache-Control", "max-age=0");
header.put("Connection", "keep-alive");
//添加頭信息
Connection conheader = connect.headers(header);
//使用get()請求頁面內容
Document document = conheader.get();
//輸出頁面內容
System.out.println(document);
//同時,jsoup 還提供瞭解決特殊請求的方法,例如連接超時問題(Connect Timeout)。具體如下:
//設置延遲時間,5000指5秒
Document doc = Jsoup.connect("網頁地址").timeout(5000).get();
System.out.println(doc);

jsoup 另外一個重要用途是解析 HTML 文件

在開始用法之前,必須弄清 jsoup 中的 Node、Element、Document 的相關概念及區別,防止因概念混淆而導致亂用錯用。

Node(節點):HTML 中所包含的內容都可以看成一個節點。

節點有很多種類型:
	屬性節點(Attribute)、
	註釋節點(Note)、
	文本節點(Text)、
	元素節點(Element)等。
	
解析 HTML 內容的過程,其實就是對節點操作的過程。

Element(元素):元素是節點的子集,所以一個元素也是一個節點。

Document(文檔):指整個 HTML 文檔的源碼內容。

代碼

//給定一個 HTML 字符串,jsoup 使用 Jsoup.parse(String html) 的方法,將 String 類型的 HTML 轉化成了 Document 類型,並可以使用 select 選擇器定位要解析的內容
//需要解析的HTML文本
String html = "<html><body><div id="first"> <h1>h1文本</h1> <p><strong>strong標籤</strong></p> </div>"
                + "<div>  <div id="course"> <ul> <li><a href="#" title="Jsoup">JavaScript</a></li> </ul> </div> </body></html>";

Document doc = Jsoup.parse(html); //轉化成Document
Element element = doc.select("div[id=first]").get(0); //獲取Element
String text1 = element.select("h1").text(); //從Element提取內容(抽取一個Node對應的信息)
String text2 = element.select("p").text(); //從Element提取內容(抽取一個Node對應的信息)
System.out.println("輸出解析的元素內容爲:");
System.out.println(element);
System.out.println("抽取的文本信息爲:");
System.out.println(text1 + "\t" + text2);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章