【发布时间】:2015-04-27 07:25:59
【问题描述】:
嗨,我在 html 文件解析中有一个场景。我正在使用 jsoup 解析 html 文件,解析后我想提取标题标签 (h1,h3,h4)。我使用了 doc.select() 但它只会返回标头标签值,但我的要求是我应该提取 h1 到 h3 或 h4 之间的标签,反之亦然。
<h4>SECTION 2</h4>
<p>some thing h4.....</p>
<p>some thing h4.....</p>
<p>some thing h4.....</p>
<h3>lawsuit</h3>
<p>some thing h3.....</p>
<p>some thing h3.....</p>
<p>some thing h3.....</p>
<h1>header one </h1>
所以这里首先搜索html字符串是否包含任何H1,H3,H4。 这里我们有 h4,所以包括 h4 它应该搜索下一个 h1 或 h3,直到 h3 我们提取字符串并将其放在单独的 html 文件中。
第一个 html 文件包含
<h4>SECTION 2</h4>
<p>some thing h4.....</p>
<p>some thing h4.....</p>
<p>some thing h4.....</p>
第二个html文件包含
<h3>lawsuit</h3>
<p>some thing h3.....</p>
<p>some thing h3.....</p>
<p>some thing h3.....</p>
第三个html文件包含
<h1>header one </h1>
....
....
....
这里的 html 字符串是动态的,所以我想写一个正则表达式来实现这个上下文,因为我是 java 新手,我不知道如何实现这个。 现在我使用子字符串,但我需要一个通用的方法,无论是正则表达式还是 jsoup 本身。
我试过的代码是。
try {
File sourceFile = new File("E://data1.html");
org.jsoup.nodes.Document doc = Jsoup.parse(sourceFile, "UTF-8");
org.jsoup.nodes.Element elements = doc.body();
String elementString = StringUtils.substringBetween(elements.toString(),"<h4>", "<h3>");
System.out.println("elementString::"+elementString);
File destinationFile = new File("E://sample.html");
BufferedWriter htmlWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8"));
htmlWriter.write(elementString);
htmlWriter.close();
System.out.println("Completed!!!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
请帮助我实现这一目标。
【问题讨论】:
-
适用于您的第一个 html 的基本正则表达式是 here。虽然不能让它工作得很好。