Jsoup

官网:http://jsoup.org/
 jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据
使用例子:

输出百度首页的所有链接地址:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;



public class JsoupTest {
public static final int READ_TIMEOUT = 120000;
public static final String CHROME_USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.107 Safari/534.13";

public static void main(String[] arsg) throws IOException{

Document doc = Jsoup.connect("http://www.baidu.com/").userAgent(CHROME_USER_AGENT).timeout(READ_TIMEOUT).get();


//Element content = doc.getElementById("content"); doc.getAllElements();
Elements contentall =  doc.getElementsByTag("a");
for (Element content:contentall){

  String linkHref = content.attr("href");
  String linkText = content.text();
  System.out.println(linkHref);
  System.out.println(linkText);
  System.out.println("----------------------------------");
/*Elements links = content.getElementsByTag("a");
for (Element link : links) {
  String linkHref = link.attr("href");
  String linkText = link.text();
  System.out.println(linkHref);
  System.out.println(linkText);
  System.out.println("----------------------------------");
} */
}


}

}

你可能感兴趣的:(java)