【问题标题】:How to correctly download the text from website and put it into .txt? [closed]如何正确从网站下载文本并将其放入.txt? [关闭]
【发布时间】:2018-06-17 15:47:13
【问题描述】:

我正在尝试从某个网站下载所有文本并将其放入文本文件中。我有类似的东西,但它所做的只是下载第一句话而不是所有文本。有人可以告诉我我做错了什么吗?感谢您的帮助,对不起我的英语,我是初学者。

    Connection connect = Jsoup.connect("http://www.onet.pl/");

    try {
        Document document = connect.get();
        Elements links = document.select("span.title");
        PrintWriter out = new PrintWriter("popular_words.txt");

        for (Element elem : links) {
            if (elem.hasText()) {
                out.append(elem.text());
            }
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


}

【问题讨论】:

    标签: java text web connection printwriter


    【解决方案1】:

    在循环外关闭PrintWriter,否则第一次迭代后会关闭,下一次迭代会抛出异常。

    Connection connect = Jsoup.connect("http://www.onet.pl/");
    
            try {
                Document document = connect.get();
                Elements links = document.select("span.title");
                PrintWriter out = new PrintWriter("popular_words.txt");
    
                for (Element elem : links) {
                    if (elem.hasText()) {
                        out.append(elem.text());
                    }
    
                }
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    

    【讨论】:

    • 谢谢,我什至没有注意到 :)
    【解决方案2】:

    获取线路 out.close(); 在 if 语句之外,将其置于其下方并重试可能是原因,如果它没有通过打印所选元素的数量来检查您的选择条件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2010-10-06
      • 2015-09-28
      • 1970-01-01
      • 2016-07-09
      • 2016-05-13
      相关资源
      最近更新 更多