Jousp解析Html內容

需求:需要獲取另外網站頁面的內容數據
前期想之前在前臺用js來解析,發現有跨域問題,解決起來很麻煩。
所以決定在後臺使用jousp解決

引用
https://blog.csdn.net/qq_37933685/article/details/85233318
此PO介紹十分詳細,有需要的可以去仔細瞭解。

1、首先引用jousp的jar包,直接在pom.xml引入即可。

		 <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
 		</dependency>

首先連接到需要訪問的url-------------Jsoup.connect()

try
{
    Document document = Jsoup.connect("http://www. weibo.com").get();
    System.out.println(document.title());
} 
catch (IOException e) 
{
    e.printStackTrace();
}

此後就可同樣操作
//通過class查詢
document.getElementsByClass(“page_nav page”)
以此獲取相應的數據

尋找元素

  • getElementById(String id) getElementsByTag(String tag)

  • getElementsByClass(String className) getElementsByAttribute(String
    key) (及相關方法)

  • 元素的兄弟姐妹:siblingElements(),firstElementSibling(),
    lastElementSibling(),nextElementSibling(),previousElementSibling()

  • 圖:parent(),children(),child(int index)

處理元素數據

  • attr(String key)獲取和attr(String key, String value)設置屬性
  • attributes() 獲得所有屬性
  • id(),className()和classNames()
  • text()獲取和text(String value)設置文本內容
  • html()獲取和html(String value)設置內部HTML內容
  • outerHtml() 獲取外部HTML值
  • data()獲取數據內容(例如script和style標籤)
  • tag() 和 tagName()

操縱HTML和文本

  • append(String html), prepend(String html)
  • appendText(String text), prependText(String text)
  • appendElement(String tagName), prependElement(String tagName)
  • html(String value)

更多詳盡請查閱api文檔

貼一個Demo
獲取Table內數據

Document waterdocument;
			try {
				waterdocument = Jsoup.connect(waterUrl).header("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36").get();
				//表格
				Elements waterelements = waterdocument.getElementsByClass("data_table");
				//select("table#table_style_e");
				for(Element element:waterelements){
					if(element.text()!=null&& !"".equals(element.text())){
						 Elements es = element.select("tr");
						 for(Element tdelement:es){
							 Elements tdes = tdelement.select("td");
							 for(int i = 0; i < tdes.size(); i++){
								
								//do something
							 }
						 }
					 }
				 }
				
			} catch (IOException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}

補上一個例子
在這裏插入圖片描述
我需要獲取到2019年12月02日的text
但這個div 沒有專屬的class 。
頂部的class爲itablist block
直接獲取獲取會把下面data_table中的數據一起打印出來,這不是我想要的。
所以採用remove()
反向獲得年份的數據

Elements  elements = document.getElementsByClass("itablist block").first().children().select("div:not(.data_table)").remove();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章