How to Use groovy to parse HTML code that cannot pass XML Verification
Original article: robust HTML parsing the groovy way
Parsing XML with groovy is simple, and it can run well as long as the input data format is good-but it is not always guaranteed in reality. Considering the HTML code, it is always difficult to verify them through XML, which requires tagsoup to save.
The main obstacle is:
- DTD
- Unclosed labels
Let's use a simple script to demonstrate parsing the stackoverflow page
[Java]View plaincopy
- Def slurper = new xmlslurper ()
- Def htmlparser = slurper. parse ("http://stackoverflow.com /")
- Htmlparser. '**'. findall {It. @ class = 'Question-hyperlink'}. Each {
- Println it
- }
The script accesses the homepage of stack overflow and prints all items with the 'Question-hyperlink' attribute. But the runtime throws the following exception: Caught: Java. Io. ioexception: server returned HTTP response code: 503 for URL: http://www.w3.org/TR/html4/strict.dtd at html_parser.run (html_parser.groovy: 7)
Note: This problem no longer exists after it is upgraded to groovy 1.8.
Xmlslurper encountered problems when parsing html dtd, which can be solved through another blog.
[Java]View plaincopy
- Def slurper = new xmlslurper ()
- Slurper. setfeature ("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
- Def htmlparser = slurper. parse ("http://stackoverflow.com /")
- Htmlparser. '**'. findall {It. @ class = 'Question-hyperlink'}. Each {
- Println it
- }
However, the script reports an error again because of unclosed tags. Here, tagsoup is used to solve this problem. Best of all, tagsoup and xmlslurper can work very well. The following is an example:
[Java]View plaincopy
- @ Grab (group = 'org. ccil. Cowan. tagsoup ', module = 'tagsoup', version = '1. 2 ')
- Def tagsoupparser = new org. ccil. Cowan. tagsoup. Parser ()
- Def slurper = new xmlslurper (tagsoupparser)
- Def htmlparser = slurper. parse ("http://stackoverflow.com /")
- Htmlparser. '**'. findall {It. @ class = 'Question-hyperlink'}. Each {
- Println it
- }
The first line is used to obtain the tagsoup library, and then the tagsoupparser instance is assigned to xmlslurper.
This article Reprinted from http://blog.csdn.net/hiarcs/article/details/6628062