package jsoup;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;
import java.io.File;
import java.net.URL;
public class JsoupFirstTest {
@Test
public void testUrl() throws Exception{
//解析URL地址
Document doc =Jsoup.parse(new URL("http://www.itcast.cn"),1000);
//使用標簽選擇器,獲取title標簽中的內容
String title=doc.getElementsByTag("title").first().text();
//將獲取到的信息進行打印
System.out.println(title);
}
@Test
public void testString() throws Exception{
//使用工具類讀取文件,獲得字符串
String content= FileUtils.readFileToString(new File("C:\\Users\\Administrator\\Desktop\\bolg_add.html"),"utf8");
//解析字符串
Document doc=Jsoup.parse(content);
String string=doc.getElementsByTag("title").first().text();
System.out.println(string);
}
@Test
public void testFile() throws Exception{
Document doc=Jsoup.parse(new File("C:\\Users\\Administrator\\Desktop\\bolg_add.html"),"utf8");
String title=doc.getElementsByTag("title").first().text();
System.out.println(title);
}
}
上面代碼就是利用jsoup對URL、字符串、文件的解析,這也是Jsoup的三大常用功能。
在進行以上代碼的驗證是,必須提前進行依賴的引入。