How to save a jsoup document as text file

与世无争的帅哥 提交于 2019-12-11 03:23:26

问题


I am trying to save all of the readable words on a web page into one text document while ignoring html markup. Using JSoup to parse all of the words on a webpage, my only guess of how to seperate the real words from the code is through elements.

Is it possible to convert multiple elements of the jsoup document into a text file?

i.e.:

        Elements titles = doc.select("title");
        Elements paragraphs = doc.select("p");
        Elements links = doc.select("a[href]"); 
        Elements smallText = doc.select("a");

Currently saving the parse as a document with:

 Document doc = Jsoup.connect("https:// (enter a url)").get();

回答1:


Its simple way

Document doc = Jsoup.connect("https:// (enter a url)").get();
        BufferedWriter  writer = null;
        try
        {
            writer = new BufferedWriter( new FileWriter("d://test.txt"));
            writer.write(doc.toString());

        }
        catch ( IOException e)
        {
        }



回答2:


Adding answer because I am unable to comment above.

Replace writer.write(doc.toString()); by writer.write(doc.select("html").text()); in the above code.

It will give you the text on the page.

Instead of "html" in doc.select("**html**").text() other tags can be used to extract text enclosed in those tags.

Edit: you can also use writer.write(doc.body().text());




回答3:


After writing in the text with writer.write(doc.text()); the very next line you need to write writer.close(); this will fix the problem.



来源:https://stackoverflow.com/questions/43085465/how-to-save-a-jsoup-document-as-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!