【问题标题】:extract the main part of a page in java在java中提取页面的主要部分
【发布时间】:2011-03-09 18:38:25
【问题描述】:

你好 我在维基百科中有一个个性页面,我想用 java 源代码从主要部分提取代码 HTML。

你有什么想法吗?

【问题讨论】:

  • 特别是关于维基百科:有一个 API。如果您不想使用它,您至少应该调用页面like this 以减少传输大小。

标签: java html html-content-extraction


【解决方案1】:

使用 Jsoup,特别是 selector syntax

Document doc = Jsoup.parse(new URL("http://en.wikipedia.org/", 10000);
Elements interestingParts = doc.select("div.interestingClass");

//get the combined HTML fragments as a String
String selectedHtmlAsString = interestingParts.html();

//get all the links
Elements links = interestingParts.select("a[href]");

//filter the document to include certain tags only
Whitelist allowedTags = Whitelist.simpleText().addTags("blockquote","code", "p");
Cleaner cleaner = new Cleaner(allowedTags);
Document filteredDoc = cleaner.clean(doc);

它是一个非常有用的 API,用于解析 HTML 页面和提取所需数据。

【讨论】:

    【解决方案2】:

    对于维基百科有 API:http://www.mediawiki.org/wiki/API:Main_page

    【讨论】:

      【解决方案3】:
      • 分析网页结构
      • 使用JSoup解析HTML

      【讨论】:

      • 这样做可能不合法
      【解决方案4】:

      请注意,这会返回 HTML 源代码的 STRING(某种类型的 blob),而不是格式良好的内容项。

      我自己用这个 - 我有一点 sn-p 来满足我的需要。传入 url、任何开始和停止文本或布尔值以获取所有内容。

      public static String getPage(
            String url, 
            String booleanStart, 
            String booleanStop, 
            boolean getAll) throws Exception {
          StringBuilder page = new StringBuilder();
          URL iso3 = new URL(url);
          URLConnection iso3conn = iso3.openConnection();
          BufferedReader in = new BufferedReader(
              new InputStreamReader(
                  iso3conn.getInputStream()));
          String inputLine;
      
          if (getAll) {
            while ((inputLine = in.readLine()) != null) {
              page.append(inputLine);
            }
          } else {    
            boolean save = false;
            while ((inputLine = in.readLine()) != null) {
              if (inputLine.contains(booleanStart)) 
                save = true;
              if (save) 
                page.append(inputLine);
              if (save && inputLine.contains(booleanStop)) {
                break;
              }
            }
          }
          in.close();
          return page.toString();
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-02
        相关资源
        最近更新 更多