简体   繁体   中英

How to extract body contents from html file with more than one html tags with jsoup

I need to parse an html file, containing more than one html tags, with jsoup.

I split the document into many html elements and I am able to extract some tags, like title

Document doc = Jsoup.parse(file, "UTF-8");
Elements el = doc.getElementsByTag("html");
for (Element e : el) {
   writer = new PrintWriter(output);
   writer.println(e.select("title"));
   writer.println(e.select("body"));
   writer.close();
}

Output

<title>titletext</title>

but it seems to ignore the existance of the body tag in every element.

Using Document.body() just spits all the contents of the body tags together.

Since I can't get a Document from each Element to use body() on, how can I extract the body tag from each Element seperately?

Assumed you have such a file :

<!DOCTYPE html>
<html>
<head>
<title>Page Title 1</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph on page 1.</p>
</body>
</html> 

<html>
<head>
<title>Page Title 2</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph on page 2.</p>
</body>
</html> 

<html>
<head>
<title>Page Title 3</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph on page 3.</p>
</body>
</html> 

you can split your file at the end of each html part (</html>) and parse each part separately. Example :

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class JsoupTest {

    public static void main(String argv[]) throws IOException {
        String multihtml = new String(Files.readAllBytes(Paths.get("C:\\users\\manna\\desktop\\test.html")));
        String [] htmlParts = multihtml.split("(?<=</html>)");
        Document doc;  

        for(String part : htmlParts){
            doc = Jsoup.parse(part);
            System.out.println("");
            System.out.println("title : "+doc.title());
            System.out.println("");
            System.out.println(doc.body().outerHtml());
            System.out.println("******************************************");            
        }       
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM