【问题标题】:Java get content from url [duplicate]Java从url获取内容[重复]
【发布时间】:2021-07-08 21:14:14
【问题描述】:

我正在尝试使用 java 从 url 获取文本。 我在谷歌上找到了这个答案:

URL url = new URL("https://www.google.com");
Scanner s = new Scanner(url.openStream());
    
System.out.println(s);

但是我怎样才能得到页面的标题呢?文本?如何选择从 url 中获取什么?

【问题讨论】:

  • 你可能需要一个像 JSoup 这样的库

标签: java url


【解决方案1】:

您可以使用一些javax.swing.text.html 实用程序类。

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
//...
try{
    HTMLEditorKit htmlEditKit = new HTMLEditorKit();
    HTMLDocument htmlDocument = (HTMLDocument) htmlEditKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    parser.parse(new InputStreamReader(new URL("https://www.google.com").openStream()),
            htmlDocument.getReader(0), true);
    System.out.println(htmlDocument.getProperty("title"));
} catch(IOException e){
    //Handle
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 2012-02-23
    • 2019-09-23
    • 2013-10-09
    • 2014-09-19
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多