項目源碼:請別搶我閃刀姬/天氣預報
前言
本來是打算用C#爬取天氣網站上的信息,然後用正則表達過濾有用信息的,但是很淦,正則表達式太難了。無意間找到添加web引用的方式來獲取天氣信息,親自測試後發現效果尚可,就記錄一下。
引用部分
由於本次是控制檯應用,就沒有頁面設計了。在VS中新建控制檯程序後,右擊“引用”——“添加服務引用”。
在“添加服務引用”左下角選擇“高級”。
在“服務引用設置中”選擇左下角的“添加web引用”。
在其中輸入天氣預報提取網址的url:
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
至此,引用功能就已完成。該網站提供了很多查詢方法,此處我們使用的是getWeatherCityName(),方法詳細內容如下:
當然,你也可以轉到該url查看更多定義,選擇適合你的方法。
代碼實現部分
Main方法裏直接引用:
WeatherWebService myweather = new WeatherWebService();
string[] myweathers = myweather.getWeatherbyCityName("鄭州");
for (int i = 0; i < myweathers.Length;i++ )
{ Console.WriteLine(myweathers[i]); }
傳入的值儘量不要帶“市”,返回的數組循環輸出後結果如下:
其中各項所代表的含義可以查看上方官網的說明,這裏爲了讓佈局好看一點,讓重點突出一點,可以使用到控制檯的字體顏色轉換語句:
Console.ForegroundColor = ConsoleColor.顏色;
完善後的代碼如下:
WeatherWebService myweather = new WeatherWebService();
string[] myweathers = myweather.getWeatherbyCityName("鄭州");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("今日天氣:\n更新時間:" + myweathers[4]);
Console.WriteLine("當前選擇地區:" + myweathers[0] + "_" + myweathers[1] + "\n");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(myweathers[6] + "(今日) 風向&風力:" + myweathers[7]);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" 氣溫:" + myweathers[5] + "\n");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("當前實況(數據每2.5小時左右自動更新一次):\n" + myweathers[10] + myweathers[11]);
Console.Write(myweathers[13] + "(明天) 風向&風力:" + myweathers[14]);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" 氣溫:" + myweathers[12] + "\n");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(myweathers[18] + "(後天) 風向&風力:" + myweathers[19]);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" 氣溫:" + myweathers[17] + "\n");
Console.ForegroundColor = ConsoleColor.White;
當然,你也可以在後面加一個判斷,輸入1的話可以查詢其他城市,然後獲取輸入的值,傳入方法中。如果感興趣的話可以看一下源碼,這裏就不再過多展示。
運行效果
結語
程序很小,僅作分享。不足之處,望見諒。