Created
April 27, 2013 03:07
-
-
Save gucheen/5471735 to your computer and use it in GitHub Desktop.
Js获取天气信息
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//看到WScript字样你应该就知道这是一个运行在宿主上面的脚本了 | |
//因为运用到的正则处理比较多,所以我用jscript作为编写语言 | |
(function(WS,City){ | |
//由于获取的内容确定是utf-8编码,而jscript的字符串处理默认就是utf-8,因此不需要编码转换了 | |
function getURL(url, method, callback) { | |
with(new ActiveXObject("msxml2.xmlhttp")) { | |
open(method, url + (url.match(/\?/) ? '&': '?') + Math.random(), 0); | |
setRequestHeader('User-Agent', | |
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31'); | |
send(); | |
callback({ | |
html: responseText | |
}); | |
} | |
} | |
var logs=''; | |
function log(x) { | |
//把结果一次性输出 | |
if(!x)WS.echo(logs); | |
else logs+=x+'\n'; | |
} | |
function fo(tag) { | |
//在tag字符串外面画一个框 | |
//整个代码就这玩意没什么实际用处。。 | |
var l = tag.match(/[\x00-\xff]+|$/g).join('').length + | |
tag.match(/[^\x00-\xff]+|$/g).join('').length * 2; | |
var b1 = new Array(40).join('*'), | |
b2 = new Array(20 - (l >> 1)).join(' '), | |
b3 = WS.fullname.match(/cscript/i)? '*' + new Array(38).join(' ') + '*': '', | |
b4 = new Array(40 - l - 20 + (l >> 1) - 1).join(' '); | |
return [b1, b3, '*' + b2 + tag + b4 + '*', b3, b1].join('\n'); | |
} | |
//从百度获得当前所在地的地区代码 | |
getURL('http://www.baidu.com/s?wd=' + encodeURI((City||'')+'天气'), 'GET', function(obj) { | |
//从天气预报网数据接口获得数据 | |
getURL('http://m.weather.com.cn/data/' + | |
obj.html.replace(/^[\s\S]+?http\:\/\/www.weather.com.cn\/weather\/(\d+)[\s\S]+$/gi, | |
'$1') + '.html', 'GET', | |
function(obj) { | |
//fx和fp用来使输出整齐些 | |
function fx(n) { | |
var d = new Date(); | |
d.setDate(d.getDate() + n - 1); | |
return fp([d.getFullYear(), d.getMonth() + 1, d.getDate() + (i < 4 ? '(' + | |
'今明后'.charAt(i - 1) + '天)': '')].join('-'), i < 4 ? 2 : 0) + '星期' + | |
'日一二三四五六'.charAt(d.getDay()); | |
} | |
function fp(x, i) { | |
return new Array(20).join(' ').replace(new RegExp("^ {" + (x.length + i) + "}", 'i'), x); | |
} | |
var json; | |
//解析json | |
eval('json=' + obj.html); | |
var jw = json.weatherinfo; | |
with(jw) { | |
log(fo(city + '天气预报情况')); | |
//输出日期,温度和天气 | |
for (var i = 1; i <= 6; i++) log([fx(i), jw['temp' + i], jw['weather' + i]].join(' ') + '\n'); | |
} | |
}); | |
}); | |
log(); | |
})(WScript,'上海'); | |
//第二个参数可不填,默认查询当前地区 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment