這兩天搞個天氣預報,記得以前用.net版本有種是抓取百度天氣寫入txt,再讀取。時間久了,txt很多。感覺不是很好。百度了一下,找了點別人的方法改進了一下。
取得天氣網址:http://www.weather.com.cn/html/weather/101210701.shtml這裡是溫州的,當然其他城市自己搜尋一下,換一下ID。
由於是寫入cookies記錄當天天氣,所有需要在網站下瀏覽。
js程式碼:
複製代碼代碼如下:
var Url=escape(http://m.weather.com.cn/data/101210701.html);
var COOKIE_info = COOKIE_info;
var date = new Date();
var Hours=24-date.getHours()-1;
var Mins=60-date.getMinutes()-1;
var Secs=60-date.getSeconds();
date.setTime(date.getTime() + (1 * Hours * 60 * 60 * 1000) + (1 * 1 * Mins * 60 * 1000) + (1 * 1 * 1 * Secs * 1000));
var RD_cookie_info= $.cookie(COOKIE_info);
$(function(){
if(RD_cookie_info==null)
{
Getdata(Url);
}
else{
$(#weather).html(RD_cookie_info);
}
})
function Getdata(Url)
{
$.ajax({
type:GET,
cache: false,
url: AjaxGet.asp,
data:Url=+Url,
dataType: html,
error: function(){$(#weather).html(讀取失敗...請刷新重試!);},
success: function(json){
var t = '('+json+')';
var result = eval(t);
var Getinfo=;
Getinfo+=result.weatherinfo.date_y+ ;//年月日
Getinfo+=result.weatherinfo.date+ ;//農曆年月日
Getinfo+=result.weatherinfo.week+ ;//星期幾
Getinfo+=<br />;//換行
Getinfo+=result.weatherinfo.city;//取得城市名稱
Getinfo+= <img src=/http://m.weather.com.cn/img/c+result.weatherinfo.img1+.gif//> //天氣圖片1
Getinfo+=<img src=/http://m.weather.com.cn/img/c+result.weatherinfo.img2+.gif//> ;//天氣圖片2
Getinfo+=result.weatherinfo.weather1+ ;//天氣狀況
Getinfo+=result.weatherinfo.temp1;//溫度
$.cookie(COOKIE_info,Getinfo, { path: '/', expires: date });
$(#weather).html(Getinfo);
}
});
}
html代碼:
複製代碼代碼如下:
<div id=weather style=font-size:12px;></div>
這個是用網路上常見的asp抓取,當然也可以換成.net抓取或其他。