2013-02-27 44 views
2

我是一个java新手。是否有可能从网站获取数据,然后将其存储在某种数据结构中?例如,该计划在给定时间从雅虎财务获取股票的价值并存储它。就像我说的那样,我对Java并不熟练,我想知道这是否可以完成。如果可以的话,这样做很难吗?在Java中检索数据

+2

是的,它可以做到,是的,它很难(从你的洞察力)。您需要了解如何处理如何处理“URLConnection”,基本I/O和字符串解析。你甚至可能需要了解JDBC。有了一些经验,不,这并不难。不过,我会从一些基础入手。尝试阅读本地驱动器的HTML文件。一旦你理解了'String'解析的基础,请尝试下载它。 – MadProgrammer 2013-02-27 04:01:34

+3

你在说网络抓取。 Java中有一个很好的库,可以帮助你做到这一点,称为JSoup。 – 2013-02-27 04:02:18

+0

很有可能,您试图从中获得它的网站已经具有编程的更多轻松检索的Web服务,您可以在没有繁琐的HTML解析的情况下进行爬网 – amphibient 2013-02-27 18:16:15

回答

0

是的,您可以将任意网页下载到Java字符串并解析内容,但是这样的解决方案将不可靠。如果作者更改网站的结构,您的代码将立即崩溃。

做这种整合的流行方式是RESTful web service。数据提供者将拥有一组可以调用的URL &参数,并返回股票价格数据(以xml或JSON格式)

0

是的,它可以借助web服务。

  1. 雅虎或其他将公开网络服务。
  2. 你的程序将消耗该Web服务,并获取数据,并在您的最终
1

我用JSoup广泛做处理。如果您只需要自定义一个程序从布局或结构不经常更改的网站提取数据,JSoup就足够了,方便。

假设你知道如何编程(不一定熟悉的Java)的基本原理,了解什么是网络(例如,什么是htmldom,等等),我希望你拿起怎么办网站用JSoup拼凑很快。

3
public class GetYahooData 
    { 
     public ArrayList<JSONObject> getOutputFromUrl(String url) 
     { 
      ArrayList<JSONObject> output = new ArrayList<JSONObject>(); 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      HttpResponse response; 
      StringBuilder builder= new StringBuilder(); 
      JSONObject myjson ; 
      JSONArray the_json_array; 
      try 
      { 
       response = httpClient.execute(httpPost); 
       BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
       char[] buf = new char[8000]; 
       int l = 0; 
        while (l >= 0) 
        { 
         builder.append(buf, 0, l); 
         l = in.read(buf); 
        } 
       myjson = new JSONObject("{child:"+builder.toString()+"}"); 
       JSONObject mmm = new JSONObject(builder.toString()); 
       JSONArray mmmArr = mmm.getJSONArray("status"); 
       the_json_array = myjson.getJSONArray("child"); 
       for (int i = 0; i < the_json_array.length(); i++) 
       { 
        JSONObject another_json_object = the_json_array.getJSONObject(i);//the_json_array.getJSONObject(i); 
        output.add(another_json_object); 
       } 
      } catch (ClientProtocolException e) { 
       System.out.println("ClientProtocolException :"+e); 
       e.printStackTrace(); 
      } catch (IOException e) { 
       System.out.println("IOException :"+e); 
       e.printStackTrace(); 
      } catch (JSONException e) { 
       System.out.println("JSONException hussain :"+e); 
       e.printStackTrace(); 
      } 
      return output; 
     } 
    } 

public class useYahoo 
{ 
    public static void main(String args[]) 
    { 
     String url = "the url you want the response from"; 
     getYahooData object = new GetYahooData(); 
     ArrayList<JSONObject> output = object.getOutputFromUrl(url); 
    } 
}