打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Google爬取天气预报代码
文章分类:Java编程

用了国内的几个web service的天气预报服务,打着中央气象局的幌子,本来用的还好好地,过了几天,发现不能调用了,原来是服务器超过请求次数了,Free到这种程序,对国内的Free服务深感失望,心想还是用一直信赖的Google吧,所以就有了以下利用Http请求爬取Google天气预报的代码,并将请求过的城市天气预报按天缓存一下:

 

示例程序效果地址:http://weather.faqee.com/

 

所有代码如下:

 

Java代码
  1. public NodeList getWeatherDiv(String htmlUrl) {   
  2.     NodeList res = null;   
  3.     try{   
  4.         Parser parser = new Parser(htmlUrl);   
  5.         parser.setEncoding("GBK");   
  6.   
  7.         NodeFilter divFilter = new NodeClassFilter(Div.class);   
  8.   
  9.         OrFilter lastFilter = new OrFilter();   
  10.         lastFilter   
  11.                 .setPredicates(new NodeFilter[] { divFilter });   
  12.   
  13.         NodeList nodeList = parser.parse(lastFilter);   
  14.         Node[] nodes = nodeList.toNodeArray();   
  15.   
  16.         for (int i = 0; i < nodes.length; i++) {   
  17.             Node anode = (Node) nodes[i];   
  18.             if(anode instanceof Div){   
  19.                 Div mydiv = (Div)anode;   
  20.                 String className = mydiv.getAttribute("class");   
  21.                 if(className!=null && className.equals("e")){   
  22.                     res = mydiv.getChildren();   
  23.                 }   
  24.             }   
  25.         }   
  26.     } catch (ParserException e) {   
  27.         e.printStackTrace();   
  28.     }   
  29.     return res;   
  30. }       
  31.       
  32.    public static void cleanCache() {    
  33.     if(isStart) return;   
  34.     isStart = true;   
  35.        TimerTask task = new TimerTask() {    
  36.            public void run() {           
  37.             Iterator it = hmCache.entrySet().iterator();   
  38.             while (it.hasNext()) {   
  39.                 Map.Entry entry = (Map.Entry) it.next();   
  40.                 Object key = entry.getKey();    
  41.                 String today = DateTimeUtil.format(new Date(),"yyyyMMdd");   
  42.                 if(key.toString().indexOf(today)>=0){   
  43.                     it.remove();   
  44.                     hmCache.remove(key);   
  45.                 }          
  46.             }                  
  47.            }    
  48.        };    
  49.        Timer timer = new Timer();    
  50.        timer.schedule(task, Calendar.getInstance ().getTime(), 24*3600 * 1000);    
  51.   
  52.     }      
  53.   
  54.       
  55.    private void addWeatherDay(JSONObject json,int flag,String htmlContent){   
  56.     String tt = (flag==0?"t":("t"+flag));   
  57.     try{   
  58.   
  59.             Node anode = null;   
  60.             Parser parser = Parser.createParser(htmlContent, "GBK");   
  61.             NodeFilter textFilter = new NodeClassFilter(TextNode.class);   
  62.             NodeFilter imgFilter = new NodeClassFilter(ImageTag.class);   
  63.                
  64.             OrFilter lastFilter = new OrFilter();   
  65.             lastFilter.setPredicates(new NodeFilter[] { textFilter,imgFilter });   
  66.             //String t = "",t_res = "",t_tp="";   
  67.             NodeList nodeList = parser.parse(lastFilter);   
  68.             Node[] nodes = nodeList.toNodeArray();   
  69.             for (int i = 0; i < nodes.length; i++) {   
  70.                 anode = (Node) nodes[i];   
  71.                 if(anode instanceof ImageTag){   
  72.                     ImageTag img = (ImageTag)anode;   
  73.                     if(img!=null){   
  74.                         json.put(tt+"_res", img.getAttribute("title"));   
  75.                         json.put(tt+"_result", img.getAttribute("title"));   
  76.                         json.put(tt+"_tp", ("http://www.google.cn"+img.getImageURL()));   
  77.                     }   
  78.                 }else if(anode instanceof TextNode){   
  79.                     TextNode text = (TextNode)anode;   
  80.                     String t = text.getText();   
  81.                     if(t.indexOf("°C")>0){   
  82.                         json.put(tt, t);   
  83.                     }   
  84.                 }   
  85.             }   
  86.   
  87.     }catch(Exception ex){   
  88.         ex.printStackTrace();   
  89.     }   
  90.    }   
  91.       
  92. private void getDivText(JSONObject json, String htmlContent) {   
  93.     String line = "";   
  94.     Node anode = null;   
  95.     Div divnode = null;   
  96.     try {   
  97.         Parser parser = Parser.createParser(htmlContent, "GBK");   
  98.         NodeFilter divFilter = new NodeClassFilter(Div.class);   
  99.         OrFilter lastFilter = new OrFilter();   
  100.         lastFilter.setPredicates(new NodeFilter[] { divFilter });   
  101.   
  102.         NodeList nodeList = parser.parse(lastFilter);   
  103.         int idx = 0;   
  104.         Node[] nodes = nodeList.toNodeArray();   
  105.         for (int i = 0; i < nodes.length; i++) {   
  106.             anode = (Node) nodes[i];   
  107.             line = "";   
  108.             if (anode instanceof Div) {   
  109.                 divnode = (Div) anode;   
  110.                 String className = StrCharUtil.formatNullStr(divnode.getAttribute("class"));   
  111.                 String align = StrCharUtil.formatNullStr(divnode.getAttribute("align"));   
  112.                 if(align.equals("")) continue;   
  113.                 if(className.equals("") && align.equals("center")){   
  114.                     line = divnode.getChildrenHTML();   
  115.                     addWeatherDay(json,idx,line);   
  116.                     idx ++;   
  117.                 }   
  118.                    
  119.             }   
  120.             if (StrCharUtil.formatNullStr(line).equals(""))   
  121.                 continue;   
  122.         }   
  123.     } catch (ParserException pe) {   
  124.         pe.printStackTrace();   
  125.     }   
  126. }       
  127.       
  128. public JSONObject getWeather(String city){   
  129.     String today = DateTimeUtil.format(new Date(),"yyyyMMdd");   
  130.     if(hmCache.get(city+today)!=null){   
  131.         return hmCache.get(city+today);   
  132.     }          
  133.     JSONObject hm =new JSONObject();   
  134.     hm.put("zhishu","");   
  135.        
  136.          
  137.     try{   
  138.         city = getCityName(city);   
  139.         final String googleWeatherURL = "http://www.google.cn/search?hl=zh-CN&newwindow=1&q=tq+"+URLEncoder.encode(city,"UTF-8")+"&aq=f&oq=";   
  140.            
  141.         NodeList nodeListDiv = getWeatherDiv(googleWeatherURL);   
  142.         int idx = 0;   
  143.         if(nodeListDiv!=null){   
  144.             getDivText(hm,nodeListDiv.toHtml());   
  145.         }   
  146.            
  147.            
  148.     }catch(Exception ex){   
  149.         ex.printStackTrace();   
  150.     }   
  151.        
  152.           
  153.        hmCache.put(city+today, hm);   
  154.     return hm;   
  155. }  
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用Lucene进行全文检索(二)---得到有效的内容
htmlParser使用教程
定时抓取特定网站内容
利用htmlparser进行网页信息的抽取
HTMLPARSER学习小结 - jackyrong - JavaEye技术网站
html parser
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服