从 HTML Java 中提取文本

发布于 2024-08-03 13:14:34 字数 819 浏览 6 评论 0原文

我正在开发一个程序,该程序下载 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 循环,它会告诉程序继续写入文件,直到该行包含

标记,方法是:

while ((s = br.readLine()) !=null) {
    if(s.contains("<p>")) {
        while(!s.contains("</p>") {
            try {
                out.write(s);
            } catch (IOException e) {
            }
        }
    }
}

但这行不通。有人可以帮忙吗?

I'm working on a program that downloads HTML pages and then selects some of the information and write it to another file.

I want to extract the information which is intbetween the paragraph tags, but i can only get one line of the paragraph. My code is as follows;

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) {
        }
    }
}

i was trying to add another while loop, which would tell the program to keep writing to file until the line contains the </p> tag, by saying;

while ((s = br.readLine()) !=null) {
    if(s.contains("<p>")) {
        while(!s.contains("</p>") {
            try {
                out.write(s);
            } catch (IOException e) {
            }
        }
    }
}

But this doesn't work. Could someone please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

画▽骨i 2024-08-10 13:14:34

jsoup

我非常喜欢使用的另一个 html 解析器是 jsoup。您可以通过 2 行代码获取所有

元素。

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

,或者如果您希望它们位于单独的行中,您可以迭代元素并单独将它们写出。

jsoup

Another html parser I really liked using was jsoup. You could get all the <p> elements in 2 lines of code.

Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements ps = doc.select("p");

Then write it out to a file in one more line

out.write(ps.text());  //it will append all of the p elements together in one long string

or if you want them on separate lines you can iterate through the elements and write them out separately.

小瓶盖 2024-08-10 13:14:34

jericho 是几个可能的 html 解析器之一,可以使此任务既简单又安全。

jericho is one of several posible html parsers that could make this task both easy and safe.

橪书 2024-08-10 13:14:34

JTidy 可以将 HTML 文档(甚至是格式错误的文档)表示为文档模型,使得提取

标记的内容比手动处理原始文本更加优雅。

JTidy can represent an HTML document (even a malformed one) as a document model, making the process of extracting the contents of a <p> tag a rather more elegant process than manually thunking through the raw text.

ら栖息 2024-08-10 13:14:34

尝试(如果您不想使用 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) 
                        {

                    }
                }
}

Try (if you don't want to use a HTML parser library):


        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) 
                        {

                    }
                }
}
漫漫岁月 2024-08-10 13:14:34

我已经成功使用 TagSoup &用于解析 HTML 的 XPath。

http://home.ccil.org/~cowan/XML/tagsoup/

I've had success using TagSoup & XPath to parse HTML.

http://home.ccil.org/~cowan/XML/tagsoup/

海风掠过北极光 2024-08-10 13:14:34

使用 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()方法中提取文本。

Use a ParserCallback. Its a simple class thats included with the JDK. It notifies you every time a new tag is found and then you can extract the text of the tag. Simple example:

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);
        }
    }
}

So all you need to do is set a boolean flag when the paragraph tag is found. Then in the handleText() method you extract the text.

初心 2024-08-10 13:14:34

试试这个。

 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();
}
}

Try this.

 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();
}
}
狼性发作 2024-08-10 13:14:34

您可能只是使用了错误的工具来完成这项工作:

perl -ne "print if m|<p>| .. m|</p>|" infile.txt >outfile.txt

You may just be using the wrong tool for the job:

perl -ne "print if m|<p>| .. m|</p>|" infile.txt >outfile.txt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文