package xxx.xxx.xxx;
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地址,第一个参数是访问的url,第二个参数是访问时候的超时时间
Document doc = Jsoup.parse (new URL("http://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\\tree\\Desktop\\test.html"),"utf8");
Document doc = Jsoup.parse(content);
String title = doc.getElementsByTag("title").first().text();
System.out.println(title);
}
@Test
public void testFile() throws Exception{
Document doc = Jsoup.parse(new File("C:\\User\\tree\\Desktop\\test.html"), "utf8");
String title = doc.getElementsByTag("title").first().text();
System.out.println(title);
}
}
}
结果:
虽然使用Jsoup
可以替代HTTPClient
直接发起请求解析数据,但是往往不会这样用,因为实际的开发过程中,需要使用到多线程、连接池,代理
等等方法,而jsoup对这些的支持并不是很好。所以我们一般把jsoup仅仅作为Html解析工具使用。