用Java打印网页内容

问题描述

我正在尝试使用 HttpURLconnection 类读取 https://example.com/内容。我已经删除了大括号之间的 html 标签,但是我没有删除大括号之间的单词。需要打印的单词之间也没有空格。

代码如下:

    URL url = new URL("https://example.com/");
    Scanner sc = new Scanner(url.openStream());
    StringBuffer sb = new StringBuffer();
    while(sc.hasNext()) {
        sb.append(sc.next());
         }
    String result = sb.toString();

    //Removing the HTML tags
    result = result.replaceAll("<[^>]*>"," ");
    
    System.out.println("Contents of the web page: "+result);

这是我得到的输出

网页内容:ExampleDomain body{background-color:#f0f0f2;margin:0;padding:0;font-family:-apple-system,system-ui,BlinkMacSystemFont,"SegoeUI","OpenSans","HelveticaNeue",Helvetica,Arial,sans-serif;}div{width:600px;margin:5emauto;padding:2em;background-color:#fdfdff;border-radius:0.5em;Box-shadow:2px3px7px2pxrgba(0,0.02);}a:link,a:visited{color:#38488f;text-decoration:none;}@media(max-width:700px){div{margin:0auto;width:auto;}} ExampleDomain此域用于文档中的说明性示例。您可以在未事先协调或征得许可的情况下在文献中使用此域。更多信息...

如何删除大括号之间的内容? 以及如何在句子中的单词之间放置空格?

解决方法

要删除大括号之间的内容,可以使用String#replaceAll(String,String)Javadoc

str.replaceAll("\\{.*\\}","");

此正则表达式匹配左括号和右括号之间的所有字符。所以你的代码是:

URL url = new URL("https://example.com/");
Scanner sc = new Scanner(url.openStream());
StringBuffer sb = new StringBuffer();
while (sc.hasNext()) {
    sb.append(" " + sc.next());
}
String result = sb.toString();

// Removing the HTML tags
result = result.replaceAll("<[^>]*>","");

// Removing the CSS stuff
result = result.replaceAll("\\{.*\\}","");

System.out.println("Contents of the web page: " + result);