【问题标题】:how to extract web page textual content in java? [closed]如何在java中提取网页文本内容? [关闭]
【发布时间】:2011-03-03 11:21:02
【问题描述】:

我正在寻找一种使用 jdk 或其他库从网页(最初是 html)中提取文本的方法。请帮忙

谢谢

【问题讨论】:

  • 最好的方法是使用“compile 'org.jsoup:jsoup:1.9.2'”

标签: java


【解决方案1】:

使用jsoup。这是目前最优雅的屏幕抓取库。

URL url = new URL("http://example.com/");
Document doc = Jsoup.parse(url, 3*1000);
String title = doc.title();

我就是喜欢它的CSS selector syntax

【讨论】:

  • 喜欢 jsoup,但它不执行相关的 Javascript。对于 Javascript 呈现的页面,我使用 Selenium。
【解决方案2】:
【解决方案3】:

这是一个很好地包装这些细节的简短方法(基于java.util.Scanner):

public static String get(String url) throws Exception {
   StringBuilder sb = new StringBuilder();
   for(Scanner sc = new Scanner(new URL(url).openStream()); sc.hasNext(); )
      sb.append(sc.nextLine()).append('\n');
   return sb.toString();
}

这就是它的使用方式:

public static void main(String[] args) throws Exception {
   System.out.println(get("http://www.yahoo.com"));
}

【讨论】:

    猜你喜欢
    • 2012-03-02
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多