之前做的一個小程序需要獲取天氣預報接口,使用的是中國天氣網的免費接口:
http://m.weather.com.cn/data/101010100.html ,但最近發現這個接口的天氣數據不更新了,最新的天氣是2014年2月19日的。推測可能是加了什么限制,目前網上搜到的大部分天氣接口都是這個。
下面的兩個天氣接口倒是仍然可以使用,不過一個是獲取實時天氣情況的,一個是獲取當天整體天氣情況的。對於需要獲取7天內的天氣情況,還需要找尋其他接口來實現。
http://www.weather.com.cn/data/sk/101010100.html
http://www.weather.com.cn/data/cityinfo/101010100.html
通過這幾天的測試,終於找到了一個可用的,特提供給大家。
接口獲取的就是中天氣網的手機版頁面中的數據,網址為: 首頁-中國天氣網 http://mobile.weather.com.cn/index.html。
數據是通過webclient,get方式來抓取的。這里需要指出一個需要注意的地方。
就是在webClient添加的請求頭信息中加入Referer信息,否則獲取的天氣數據不是當天的。
獲取的的數據為:
如果不加Referer頭信息,獲取到的數據為:
無論你什么時候獲取,獲取到的都是20131012這天的天氣數據。奇怪的是time是最新的,一直在更新的。由此也可以看出來,他們是加了某種過濾機制無法獲取真實的當天天氣,這也間接解釋了為什么上面提到的那個天氣接口不能使用了。
說到這里那就再加一句,開頭提到的天氣接口 http://m.weather.com.cn/data/101010100.html 即使我加了Referer信息也不能獲取當天的。
數據抓取代碼:
class Program { //參考文章:中國天氣網的數據接口研究 - Create Chen - 博客園 http://www.cnblogs.com/technology/p/3488176.html
static void Main(string[] args) { //實時天氣 // string url = "http://mobile.weather.com.cn/data/sk/101010100.html?_=1393644135884"; //穿衣指數
string url = "http://mobile.weather.com.cn/data/zsM/101010100.html?_=1393645156001"; string html = webGetHtml(url); Console.WriteLine(html); Console.ReadKey(); } //get請求
public static string webGetHtml(string url) { // string url = "http://www.cnblogs.com/";
// http://www.cnblogs.com/babycool WebClient client = new WebClient(); //設置發出請求 的URI
client.BaseAddress = url; //添加到請求頭部的信息 //GET / HTTP/1.1 //Accept: text/html, application/xhtml+xml, */* //Accept-Language: zh-CN //User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; qdesk 2.4.1263.203; Windows NT 6.1; Trident/5.0) //Accept-Encoding: gzip, deflate //Host: //Connection: Keep-Alive
client.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01"); client.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8"); //注意:Referer 一定要加,否則獲取的不是當天的。
client.Headers.Add("Referer", "http://mobile.weather.com.cn/"); client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1;Chrome/27.0.1453.110; Trident/5.0)"); //client.Headers.Add("Connection", "Keep-Alive"); //client.Headers.Add("Accept-Encoding", "gzip, deflate"); //如果是獲取網站的首頁的內容 則為 client.OpenRead("/"); //如果是獲取網站域名下的非首頁的內容 則為client.OpenRead(url); //獲取流數據
Stream webStream = client.OpenRead(url); StreamReader reader = new StreamReader(webStream, Encoding.UTF8); //獲取html代碼 // string html = reader.ReadToEnd();
return reader.ReadToEnd(); } }
轉載請注明出處。