jsoup: java HTML parser
jsoup提供了一个方便的API,用来提取和操作HTML中数据。
jsoup提供三种解析HTML的方法(scrape and parse HTML from a URL, file, or string)
1. Load a document from URL(通过URL 对象来load HTML document)。
如果你想从web上解析HTML document,从而得到web上的数据
方法:Jsoup.parse(URL url);
代码如下:
<span style="font-size:14px;">//创建一个URL 对象
URL url = new URL("http://www.baidu.com");
//3*1000 是timeout 是时间单位是毫秒
Document doc = Jsoup.parse(url, 3*1000)</span>
2. Parse document from a string(通过字符串解析HTML document)
如果你有一段html代码或者某个网站,你想得到它的内容,可以通过这个方法来解决
代码如下:
Jsoup.parse(String html)/Jsoup.connect(String url);
<span style="font-size:14px;">HTML代码
String html = "<div><p>I want to know about Jsoup</p>";
Document doc = Jsoup.parse(html);
某个网站的地址
String url = "http://www.baidu.com";
Document doc = Jsoup.connect(url);</span>
3. Load document from a file(通过文件来加载HTML document)
如果你的磁盘有HTML文件,你想解析它的内容,可以用此方法
代码如下:
Jsoup.parse(File file, String charSetName, String baseUri);
<span style="font-size:14px;">//Get the file that is on your disk
File file = new File("d:\\test.html");
//Parse this file
Document doc = Jsoup.parse(file,"utf-8","http://example.com");</span>
baseURi 的参数的意思就是当 HTML 文档使用相对路径方式引用外部文件时,jsoup 会自动为这些 URL 加上一个前缀,也就是这个 baseURi,如果没有,可以用空字符串来代替。
欢迎大家指正,谢谢!