【问题标题】:Jsoup parsing html duplication on writing to fileJsoup在写入文件时解析html重复
【发布时间】:2014-09-27 07:35:07
【问题描述】:

我似乎在两次将文本写入文件时遇到此错误,第一次格式不正确,第二次格式正确。 The method below takes in this URL after it's been converted properly. 该方法应该在分隔符的所有子项的文本转换之间打印一个换行符,这些子项是所有正文所在的分隔符“ffaq”的子项。任何帮助,将不胜感激。我对使用 jsoup 还很陌生,所以解释一下也不错。

/**
 * Method to deal with HTML 5 Gamefaq entries.
 * @param url The location of the HTML 5 entry to read.
 **/
public static void htmlDocReader(URL url) {
    try {  
        Document doc = Jsoup.parse(url.openStream(), "UTF-8", url.toString());
        //parse pagination label
        String[] num =    doc.select("div.span12").
                              select("ul.paginate").
                              select("li").
                              first().
                              text().
                              split("\\s+");
        //get the max page number
        final int max_pagenum = Integer.parseInt(num[num.length - 1]);

        //create a new file based on the url path
        File file = urlFile(url);
        PrintWriter outFile = new PrintWriter(file, "UTF-8");

        //Add every page to the text file
        for(int i = 0; i < max_pagenum; i++) {
            //if not the first page then change the url 
            if(i != 0) {
                String new_url = url.toString() + "?page=" + i;
                doc = Jsoup.parse(new URL(new_url).openStream(), "UTF-8",
                                  new_url.toString());
            }
            Elements walkthroughs = doc.select("div.ffaq");
                for(Element elem : walkthroughs.select("div")) {
                    for(Element inner : elem.children()) {
                        outFile.println(inner.text());
                    }
                }
        }
        outFile.close();
    } catch(Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

【问题讨论】:

    标签: java html jsoup printwriter


    【解决方案1】:

    对于您调用text() 的每个元素,您都会打印其结构的所有文本。 假设下面的例子

    <div>
    text of div
    <span>text of span</span>
    </div>
    

    如果您为div element 拨打text(),您将获得

    跨度的div文本

    那么如果你调用text() 获取 span 你会得到

    跨度文本

    为了避免重复,您需要使用ownText()。这将只获得元素的直接文本,而不是其子元素的文本。

    长篇大论改变这个

    for(Element elem : walkthroughs.select("div")) {
        for(Element inner : elem.children()) {
            outFile.println(inner.text());
        }
    }
    

    到这里

    for(Element elem : walkthroughs.select("div")) {
        for(Element inner : elem.children()) {
            String line = inner.ownText().trim();
            if(!line.equals(""))  //Skip empty lines
                outFile.println(line);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 2020-04-26
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      相关资源
      最近更新 更多