首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 依 IP 取得當地天氣:解析網易天氣 API 並整合

     編輯:關於ASP.NET

需求與發現

網易首頁會根據訪客 IP 自動顯示當地天氣。分析發現其流程:

  1. 載入 `https://news.163.com/util/position1.html` (iframe)。
  2. 該頁面 JavaScript 讀取 Cookie `NTES_WeatherAddr`、`theaddr`。
  3. 若無 Cookie,引入 `https://202.108.39.152/ipquery` 取得城市代碼。
  4. 對照內建城市代碼表,導向 `https://news.163.com/weather/news/qx1/{代碼}.html`。

關鍵 JavaScript 邏輯 (position1.html)

var city = ["安徽","黑龍江","山東","北京",...];
var weaths = ["58321","50953","54823","54511",...]; // 對應代碼

function getCityWeatherID(cityname) {
 for(i=0;i<\/script>");
 }
}

if (!NTES_WeatherAddr) NTES_WeatherAddr = getCityWeatherID(loc);
window.location.href = "https://news.163.com/weather/news/qx1/" + NTES_WeatherAddr + ".html";

伺服器端整合方案 (C#)

無法直接在客戶端跨域讀取網易 Cookie,需在伺服器端模擬流程:

1. 呼叫 IP 查詢 API 取得城市名

public string GetCityByIP(string ip)
{
 // 使用免費 IP 地理位置 API,如 ip-api.com、ipinfo.io 或自建資料庫
 string url = $"https://ip-api.com/json/{ip}?lang=zh-TW";
 using (WebClient wc = new WebClient())
 {
 string json = wc.DownloadString(url);
 dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
 return data.city; // 如 "Taipei"
 }
}

2. 對照城市代碼表 (需維護映射表)

Dictionary cityCodeMap = new Dictionary
{
 {"北京", "54511"}, {"上海", "58367"}, {"廣州", "59287"}, {"成都", "56294"}, {"台北", "58321"} // 需擴充
};

string GetWeatherCode(string city) => cityCodeMap.TryGetValue(city, out var code) ? code : "54511";

3. 抓取天氣頁面內容 (HttpClient + HtmlAgilityPack)

public async Task GetWeatherHtml(string code)
{
 string url = $"https://news.163.com/weather/news/qx1/{code}.html";
 using (HttpClient client = new HttpClient())
 {
 string html = await client.GetStringAsync(url);
 // 解析 HTML 擷取溫度、天氣狀態、預測等資訊
 var doc = new HtmlAgilityPack.HtmlDocument();
 doc.LoadHtml(html);
 // 依網易頁面結構撰寫 XPath/CSS Selector
 var tempNode = doc.DocumentNode.SelectSingleNode("//div[@class='temp']");
 return tempNode?.InnerText ?? "無資料";
 }
}

4. 快取策略

  • IP → 城市代碼:快取 24 小時 (同 IP 短期不變)。
  • 天氣內容:快取 30-60 分鐘 (天氣更新頻率)。
  • 使用 `MemoryCache` 或 `IDistributedCache` (Redis)。

法律與道德提醒

  • 網易天氣資料屬其智慧財產權,**直接抓取並商業使用可能侵權**。
  • 建議申請官方 API 授權,或使用開放授權的天氣服務 (OpenWeatherMap、中央氣象局開放資料、WeatherAPI 等)。
  • 若僅供內部測試/學習,請遵守 `robots.txt`、限制請求頻率、標註資料來源。

替代方案:現代天氣 API 整合

// OpenWeatherMap 範例
public async Task GetWeatherByIP(string ip)
{
 string city = await GetCityByIP(ip);
 string apiKey = "YOUR_KEY";
 string url = $"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={apiKey}&units=metric&lang=zh_tw";
 using (HttpClient client = new HttpClient())
 {
 string json = await client.GetStringAsync(url);
 return JsonConvert.DeserializeObject(json);
 }
}

總結

雖可逆向工程網易天氣邏輯,但長期維護成本高且有法律風險。正式專案請使用合法授權的天氣 API,配合 IP 定位服務,即可輕鬆實現「依 IP 顯示當地天氣」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved