Jsoup searches for dom elements, and jsoup searches for dom
Package com. open1111.jsoup;
Import org. apache. http. HttpEntity;
Import org. apache. http. client. methods. CloseableHttpResponse;
Import org. apache. http. client. methods. HttpGet;
Import org. apache. http. impl. client. CloseableHttpClient;
Import org. apache. http. impl. client. HttpClients;
Import org. apache. http. util. EntityUtils;
Import org. jsoup. Jsoup;
Import org. jsoup. nodes. Document;
Import org. jsoup. nodes. Element;
Import org. jsoup. select. Elements;
Public class Demo02 {//
Public static void main (String [] args) throws Exception {
CloseableHttpClient httpclient = HttpClients. createDefault (); // create an httpclient instance
HttpGet httpget = new HttpGet ("http://www.cnblogs.com/"); // create an httpget instance
CloseableHttpResponse response = httpclient.exe cute (httpget); // execute the get request
HttpEntity entity = response. getEntity (); // get the returned object
String content = EntityUtils. toString (entity, "UTF-8"); // sets the content encoding.
Response. close (); // close the stream and Release System Resources
Document doc = Jsoup. parse (content); // parse the webpage to get the Document Object
Elements elements = doc. getElementsByTag ("title"); // obtain all the DOM Elements of the title.
Element element = elements. get (0); // get 1st elements
String title = element. text (); // return the text of the element.
System. out. println ("webpage title:" + title );
Element element2 = doc. getElementById ("site_nav_top"); // obtain the DOM Element with id = site_nav_top
String navTop = element2.text (); // return the text of the element.
System. out. println ("slogan:" + navTop );
Elements itemElements = doc. getElementsByClass ("post_item"); // query DOM by style name
System. out. println ("======= output post_item ================ ");
For (Element e: itemElements) {// for enhanced Loops
System.out.println(e.html ());
System. out. println ("-------------");
}
Elements widthElements = doc. getElementsByAttribute ("width"); // query DOM by attribute name
System. out. println ("======= output with DOM ============== ");
For (Element e: widthElements ){
System. out. println (e. toString ());
System. out. println ("-------------");
}
Elements targetElements = doc. getElementsByAttributeValue ("target", "_ blank"); // obtain the dom element based on the attribute name and attribute value.
System. out. println ("======= output target-_ blank DOM ================== ");
For (Element e: targetElements ){
System. out. println (e. toString ());
System. out. println ("-------------");
}
}
}