[英]Text Extraction from HTML Java
我正在開發一個下載HTML頁面的程序,然后選擇一些信息並將其寫入另一個文件。
我想提取段落標記之間的信息,但我只能獲得段落的一行。 我的代碼如下;
FileReader fileReader = new FileReader(file);
BufferedReader buffRd = new BufferedReader(fileReader);
BufferedWriter out = new BufferedWriter(new FileWriter(newFile.txt));
String s;
while ((s = br.readLine()) !=null) {
if(s.contains("<p>")) {
try {
out.write(s);
} catch (IOException e) {
}
}
}
我試圖添加另一個while循環,這將告訴程序繼續寫入文件,直到該行包含</p>
標記,通過說;
while ((s = br.readLine()) !=null) {
if(s.contains("<p>")) {
while(!s.contains("</p>") {
try {
out.write(s);
} catch (IOException e) {
}
}
}
}
但這不起作用。 請有人幫忙。
我真正喜歡使用的另一個html解析器是jsoup 。 您可以在2行代碼中獲取所有<p>
元素。
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements ps = doc.select("p");
然后將其寫入另一行中的文件
out.write(ps.text()); //it will append all of the p elements together in one long string
或者如果你想要它們在不同的行上,你可以迭代元素並分別寫出來。
jericho是幾個可行的html解析器之一,可以使這項任務既簡單又安全。
JTidy可以將HTML文檔(甚至是格式錯誤的文檔)表示為文檔模型,使得提取<p>
標記內容的過程比通過原始文本手動thunking更加優雅。
嘗試(如果您不想使用HTML解析器庫):
FileReader fileReader = new FileReader(file);
BufferedReader buffRd = new BufferedReader(fileReader);
BufferedWriter out = new BufferedWriter(new FileWriter(newFile.txt));
String s;
int writeTo = 0;
while ((s = br.readLine()) !=null)
{
if(s.contains("<p>"))
{
writeTo = 1;
try
{
out.write(s);
}
catch (IOException e)
{
}
}
if(s.contains("</p>"))
{
writeTo = 0;
try
{
out.write(s);
}
catch (IOException e)
{
}
}
else if(writeTo==1)
{
try
{
out.write(s);
}
catch (IOException e)
{
}
}
}
我已成功使用TagSoup和XPath來解析HTML。
使用ParserCallback。 它是一個包含在JDK中的簡單類。 它會在每次找到新標簽時通知您,然后您可以提取標簽的文本。 簡單的例子:
import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
public class ParserCallbackTest extends HTMLEditorKit.ParserCallback
{
private int tabLevel = 1;
private int line = 1;
public void handleComment(char[] data, int pos)
{
displayData(new String(data));
}
public void handleEndOfLineString(String eol)
{
System.out.println( line++ );
}
public void handleEndTag(HTML.Tag tag, int pos)
{
tabLevel--;
displayData("/" + tag);
}
public void handleError(String errorMsg, int pos)
{
displayData(pos + ":" + errorMsg);
}
public void handleMutableTag(HTML.Tag tag, MutableAttributeSet a, int pos)
{
displayData("mutable:" + tag + ": " + pos + ": " + a);
}
public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet a, int pos)
{
displayData( tag + "::" + a );
// tabLevel++;
}
public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos)
{
displayData( tag + ":" + a );
tabLevel++;
}
public void handleText(char[] data, int pos)
{
displayData( new String(data) );
}
private void displayData(String text)
{
for (int i = 0; i < tabLevel; i++)
System.out.print("\t");
System.out.println(text);
}
public static void main(String[] args)
throws IOException
{
ParserCallbackTest parser = new ParserCallbackTest();
// args[0] is the file to parse
Reader reader = new FileReader(args[0]);
// URLConnection conn = new URL(args[0]).openConnection();
// Reader reader = new InputStreamReader(conn.getInputStream());
try
{
new ParserDelegator().parse(reader, parser, true);
}
catch (IOException e)
{
System.out.println(e);
}
}
}
所以你需要做的就是在找到段落標記時設置一個布爾標志。 然后在handleText()方法中提取文本。
試試這個。
public static void main( String[] args )
{
String url = "http://en.wikipedia.org/wiki/Big_data";
Document document;
try {
document = Jsoup.connect(url).get();
Elements paragraphs = document.select("p");
Element firstParagraph = paragraphs.first();
Element lastParagraph = paragraphs.last();
Element p;
int i=1;
p=firstParagraph;
System.out.println("* " +p.text());
while (p!=lastParagraph){
p=paragraphs.get(i);
System.out.println("* " +p.text());
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
您可能只是使用錯誤的工具來完成工作:
perl -ne "print if m|<p>| .. m|</p>|" infile.txt >outfile.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.