在java中提取页面的主要部分

时间:2011-03-09 18:38:26

标签: java html html-content-extraction

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

你有什么想法吗?

4 个答案:

答案 0 :(得分:2)

使用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页面并提取所需的数据。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

  • 分析网页的结构
  • 使用JSoup解析HTML

答案 3 :(得分:0)

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

我自己使用它 - 我需要的一小部分片段。传入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();
  }