【问题标题】:How to read a text from a web page with Java?如何使用 Java 从网页中读取文本?
【发布时间】:2012-04-07 05:19:38
【问题描述】:

我想从网页中读取文本。我不想获取网页的 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 做到这一点?

【问题讨论】:

  • 只解析 HTML 标签中的文本。从那里你可以找到你想要的信息并从那里提取它。
  • 如果您正在寻找 HTML to DOM stackoverflow.com/questions/457684/… 可以帮助您。
  • 仅供参考 - 您每次迭代都会调用 in.readLine() 两次,因此您实际上是在跳过每一个奇数行。 (只是想我应该指出这段代码中的错误,因为它是谷歌搜索使用 Java 阅读网页的第一批结果之一。)

标签: java


【解决方案1】:
} catch (MalformedURLException e) {
} catch (IOException e) {
}

至少添加 e.printStackTrace() 会为你节省很多天

【讨论】:

    【解决方案2】:

    您也可以使用HtmlCleaner jar。 下面是代码。

    HtmlCleaner cleaner = new HtmlCleaner();
    TagNode node = cleaner.clean( url );
    
    System.out.println( node.getText().toString() );
    

    【讨论】:

      【解决方案3】:

      你可能想看看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"
      

      此示例摘自他们网站上的示例。

      【讨论】:

        【解决方案4】:

        使用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();
        

        【讨论】:

          【解决方案5】:

          您必须获取使用当前代码获得的内容,然后对其进行解析并查找包含所需文本的标签。萨克斯解析器将非常适合这项工作。

          或者,如果它不是您想要的特定文本,只需删除所有标签,这样您就只剩下文本了。我想你可以使用正则表达式。

          【讨论】:

            猜你喜欢
            • 2010-09-09
            • 1970-01-01
            • 2018-01-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-03-10
            • 2014-03-24
            • 1970-01-01
            相关资源
            最近更新 更多