396
技術社區[雲棲]
天氣預報 獲取日出日落的代碼
正則兩次,group(1)獲取時,group(2)獲取分,中間以:相連
華哥幫忙寫了一個LIST,獲取GROUP的值,List再依次讀出
package com.zzk.cn; import java.awt.List; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestSun { public static void main(String[] args) { URL url = null; URLConnection conn = null; InputStream in = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL("https://www.weather.com.cn/weather/101010100.shtml"); conn = url.openConnection(); in = conn.getInputStream(); isr = new InputStreamReader(in,"utf8"); br = new BufferedReader(isr); String line = ""; String info=""; while (null != (line = br.readLine())) { //System.out.println(line); info+=line; } //System.out.println(info); Pattern p=Pattern.compile("div\\sclass=.weatherTopright.*?</div>");//正則獲取網頁大致信息 Matcher m=p.matcher(info); String s1=""; while(m.find()) { s1=m.group(); //System.out.println(s1); } String s2=""; Pattern p1=Pattern.compile("bold;.>(\\d+):(\\d+)</strong>");//正則獲取網頁日出日落信息 //Pattern p1=Pattern.compile("<(/?\\s?br\\b)>"); Matcher m1=p1.matcher(s1); //System.out.println(s1); ArrayList<String> a = new ArrayList<String>(); while(m1.find()) { //m1.group(1); String s=m1.group(1); String s0=m1.group(2); String result = s+":"+s0; a.add(result); } System.out.println(a.get(0)); System.out.println(a.get(1)); // System.out.println(a.get(2)); // System.out.println(a.get(3)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != br) { br.close(); } } catch (IOException e) { e.printStackTrace(); } br = null; try { if (null != isr) { isr.close(); } } catch (IOException e) { e.printStackTrace(); } isr = null; try { if (null != in) { in.close(); } } catch (IOException e) { e.printStackTrace(); } in = null; } } }
輸出:
07:31
16:51
最後更新:2017-04-02 06:52:16
上一篇:
關於MySQL的boolean和tinyint(1)
下一篇:
MySQL Innodb數據庫性能實踐——熱點數據性能
CCAI2017 | 王堅博士現場致辭:人工智能是推動科技發展的動力
阿裏雲與Intel聯合發布加密計算,亞洲首個雲上“芯片級”數據保護
阿裏無人零售店“淘咖啡”原來長這樣...未來線下購物要看臉了?
Ubuntu 12.10 啟用 Root 登錄
Android提高應用篇之模擬信號示波器
負載均衡進階:SLB常見問題解決方法
通過阿裏雲注冊的域名怎麼設置解析?如何登錄萬網域名控製台管理域名?
自創數據集,用TensorFlow預測股票教程 !(附代碼)
Eclipse Java注釋模板設置詳解
Jsp中使用絕對路徑${pageContext.request.contextPath }