如何使用 Java 从网页中读取文本?

新手上路,请多包涵

我想从网页上阅读文本。我不想获取网页的 HTML 代码。我找到了这段代码:

     try {
        // Create a URL for the desired page
        URL url = new URL("http://www.uefa.com/uefa/aboutuefa/organisation/congress/news/newsid=1772321.html#uefa+moving+with+tide+history");

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            str = in.readLine().toString();
            System.out.println(str);
            // str is one line of text; readLine() strips the newline character(s)
        }
        in.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }

但是这段代码给了我网页的 HTML 代码。我想在这个页面中获取整个文本。我怎样才能用 Java 做到这一点?

原文由 Rigor Mortis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 313
2 个回答

您可能想为此查看 jsoup

 String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
String text = doc.body().text(); // "An example link"

这个例子是他们网站上的一个例子的摘录。

原文由 Fabian Barney 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 JSoup

您将能够使用 css 样式选择器解析内容。

在这个例子中你可以尝试

Document doc = Jsoup.connect("http://www.uefa.com/uefa/aboutuefa/organisation/congress/news/newsid=1772321.html#uefa+moving+with+tide+history").get();
String textContents = doc.select(".newsText").first().text();

原文由 Nitzan Volman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题