【发布时间】:2014-02-24 15:11:59
【问题描述】:
我正在尝试借助 Jsoup HTML 解析库来解析这个示例 html 文件。
<html>
<body>
<p> this is sample text</p>
<h1>this is heading sample</h1>
<select name="car" size="1">
<option value="Ford">Ford</option><option value="Chevy">Chevy</option><option selected value="Subaru">Subaru</option>
</select>
<p>this is second sample text</p>
</body>
</html>
当我只提取文本时,我得到以下信息。
this is sample text this is heading sample FordChevySubaru this is second sample text
选项标签文本中没有空格或换行符。
如果 html 是这样的
<html>
<body>
<p> this is sample text</p>
<h1>this is heading sample</h1>
<select name="car" size="1">
<option value="Ford">Ford</option>
<option value="Chevy">Chevy</option>
<option selected value="Subaru">Subaru</option>
</select>
<p>this is second sample text</p>
</body>
</html>
现在在这种情况下,文本是这样的
this is sample text this is heading sample Ford Chevy Subaru this is second sample text
在选项标签的文本中有适当的空格。如何使用第一个 html 文件获得第二个输出。即如果标签中没有换行符,字符串怎么可能没有连接起来。
我在 Java 中使用以下代码。
public static String extractText(File file) throws IOException {
Document document = Jsoup.parse(file,null);
Element body=document.body();
String textOnly=body.text();
return textOnly;
}
【问题讨论】:
标签: java html-parsing jsoup information-retrieval