In the Android application development process, it is often necessary to parse HTML documents, especially the applications that crawl data by crawling Web sites, such as weather forecasts. Java's common methods for parsing HTML documents are as follows:
Use regular expressions to extract data.
is implemented as a pure string lookup location.
Use the HTML parser parser.
Use the Jsoup parser.
It is recommended that you use the Jsoup parser to parse HTML documents on the Android platform. Jsoup can use either a URL, a file that stores HTML scripts, or a string that stores HTML scripts as a data source, and then a DOM, CSS selector to find and extract data.
Use Jsoup to parse HTML files in string form as follows:
To define an HTML string to parse
String html = "+ "<body><p>parsed HTML into a doc.</p></body>To drop a string into a Document object after parsing it
Document doc = jsoup.parse (HTML);
}
The following is a specific parsing case, using Jsoup to extract the hyperlink, hyperlink text, page description, and so on from the HTML file.
//Required parsing HTML string
String html = "<p>an <a href= ' http://example.com/' ><b>example</b>< /a> link.</p> ";
//Save to Document Object
Document doc = jsoup.parse (HTML);
//Get hyperlink of first a label
Element link = doc.select ("a"). );
//Remove text content in HTML string
//The value of test here is an example link
string text = Doc.body (). text ();
//Get the property with href string
// Here the value for Linkhref is "http://example.com/"
String linkhref = link.attr ("href");
//Get the plain text inside a label
//Linktext as " Example "
String linkText = Link.text ();
//Get the entire a tag inside the string
//Here Linkouterh value is <a href=" http://example.com "& Gt;<b>example</b></a>
String linkouterh = link.outerhtml ();
//Get all of the strings inside a label (without a label)
// The Linkinnerh value here is <b>example</b>
String linkinnerh = link.html ();
Jsoup can also use the whitelist () method to organize irregular HTML formats into canonical formats, and the whitelist method defines which HTML elements and attributes can be retained, and all others are deleted. The Whitelist.basic () method allows text nodes to be passed: A, B, blockquote, BR, cite, code, DD, DL, DT, EM, I, Li, Ol, p, pre, q, small, strike, strong, sub, SUP, U, UL, and the corresponding properties, do not allow pictures to pass.
The specific usage is as follows:
String unsafe =
<p><a href= ' http://example.com/' onclick= ' stealcookies () ' >link </a></p> ";
//Call clean method to organize non-standard code
String safe = Jsoup.clean (unsafe, whitelist.basic ());
//safe for <p><a href= " http://example.com/"rel=" nofollow >link</a></p>