網易首頁會根據訪客 IP 自動顯示當地天氣。分析發現其流程:
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";
無法直接在客戶端跨域讀取網易 Cookie,需在伺服器端模擬流程:
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"
}
}
Dictionary cityCodeMap = new Dictionary
{
{"北京", "54511"}, {"上海", "58367"}, {"廣州", "59287"}, {"成都", "56294"}, {"台北", "58321"} // 需擴充
};
string GetWeatherCode(string city) => cityCodeMap.TryGetValue(city, out var code) ? code : "54511";
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 ?? "無資料";
}
}
// 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 顯示當地天氣」。