【问题标题】:parsing a webpage with java用java解析网页
【发布时间】:2012-04-01 02:18:51
【问题描述】:

我希望将来自该网页的实时费率:http://www.truefx.com/ 解析到我的 java 程序中,即我希望网页中每秒刷新的数据不断流入我的程序中.

如果可能的话,我想使用标准的 java 库来做到这一点。我知道像 jsoup 之类的插件,可能还有其他插件,但我不想下载和安装插件,因为我使用的计算机的硬盘驱动器位于加利福尼亚州,除了一些核心程序之外的所有东西,eclipse 正在运行其中,每晚系统重新启动时都会被删除。

因此,如果有人知道标准 Eclipse 下载中可以执行此操作的包,请告诉我!谢谢


好的,所以我得到了这个工作,但它似乎很慢。例如,数据将逐秒更改,即使我也在刷新我逐秒读取的网页(我使用 thread.sleep(1000)),然后获取一个新实例网页的,它每分钟左右只更新一次。什么给了?

这是我的代码的样子(我使用您在上面发布的内容作为我的 url 阅读器):

 public String getPage(String urlString){
        String result = "";
        //Access the page
        try {
         // Create a URL for the desired page
         URL url = new URL(urlString);
         // Read all the text returned by the server
         BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
         String str;
         while ((str = in.readLine()) != null) {
             // str is one line of text; readLine() strips the newline character(s)
             result += str;
         }
         in.close();             
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }          
        return result;
    }

    public static void main(String[]args){
        int i =0;
        Reading r = new Reading();

    while(true){
        try{Thread.sleep(1000);}catch(Exception e){}
        String page = new String(r.getPage("http://www.fxstreet.com/rates-charts/forex-rates/"));
        int index = page.indexOf("last_3212166");
        //System.out.println(i+page);
        i++;
        System.out.println(i+"GBP/USD: "+page.substring(index+14,index+20));
    }

【问题讨论】:

  • 标准 Java 库没有任何 HTML 解析功能。另外,你有没有亲自研究过这个?似乎一个快速的谷歌可能会出现这种情况。此外,如果每晚都删除所有内容,您如何保留源代码?编辑:实际上,看起来 Java 确实有一些内置的东西:en.wikipedia.org/wiki/Java_API_for_XML_Processing
  • 谢谢。我调查了一下,但在问之前可能会更努力地搜索一下。
  • 好吧,这并不是真的被删除了,而是更多地与类路径被重置或其他事情有关。我不完全了解系统是如何设置的,我只知道您不能永久更改类路径。

标签: java eclipse parsing standard-library


【解决方案1】:

无需外部 API,您只需导入 java.net.URL

即可通过此函数获取页面
static public String getPage(String urlString){
    String result = "";
    //Access the page
    try {
     // Create a URL for the desired page
     URL url = new URL(urlString);
     // Read all the text returned by the server
     BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
     String str;
     while ((str = in.readLine()) != null) {
         // str is one line of text; readLine() strips the newline character(s)
         result += str;
     }
     in.close();             
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }          
    return result;
}

然后使用 java.util.regex 来匹配您想从页面获取的数据。并将其解析为您的标签。不要忘记将所有这些都放在一个带有 while(true) 循环和 sleep(some_time)thread 中第二个信息。

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 1970-01-01
    • 2014-08-23
    • 2015-02-23
    • 2023-03-18
    • 2020-09-02
    • 2015-09-08
    • 2016-04-14
    相关资源
    最近更新 更多