C#爬取天气数据

C#使用WebClient爬取天气数据

天气数据地址:https://m.tianqi.com/lishi/

传入参数说明

citypy:城市拼音
historyurl:爬取地址https://m.tianqi.com/lishi/
month:月份,如202112

代码实现

爬取前一天数据

string month = DateTime.Today.AddDays(-1).ToString("yyyyMM");
void getdata(string citypy,string historyurl,string month){
	string url=historyurl+citypy+"/index.html";
	string strHTML = null;
	using (WebClient myWebClient = new WebClient { Credentials = CredentialCache.DefaultCredentials }){
    	Stream myStream = myWebClient.OpenRead(url);
        using (StreamReader sr = new StreamReader(myStream, Encoding.UTF8)){
        	strHTML = sr.ReadToEnd();
        }
     }
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(strHTML);
    var res = doc.DocumentNode.SelectNodes(@"/html[1]/body[1]/div[11]/a");
    if (res != null){
    	int index = res.Count - 2;//减去天气预报的行
        webfiled wf = new webfiled();//天气对象
        var nodes = res[index].SelectNodes(@"div");
        var date = nodes[0].InnerText.Replace(" ", "").Replace("-", "/");
        wf.dates1 = Convert.ToDateTime(date.Substring(0, 10));//日期
        wf.week = date.Substring(10);//周几
        wf.high_1 = nodes[1].InnerText.Replace("℃", "");//最高气温
        wf.low_1 = nodes[2].InnerText.Replace("℃", "");//最低气温
        wf.type_1 = nodes[3].InnerText.Trim();//天气
        wf.fx_1 = nodes[4].InnerText.Trim();//风向
        //可以继续写入数据到数据库
     }
}

爬取一个月的天气数据

var res = doc.DocumentNode.SelectNodes(@"/html[1]/body[1]/div[10]/a");
if (res != null)
{
    webfiled wf = new webfiled();
    for(int aNum = 0; aNum < res.Count; aNum++)
    {
        var nodes= res[aNum].SelectNodes(@"div");
        var date = nodes[0].InnerText.Replace(" ", "").Replace("-", "/");
        wf.dates1 = Convert.ToDateTime(date.Substring(0,10));
        if (wf.dates1 > DateTime.Today)//如果这是当前月,需要除去今天以后的天气预报,
            break;
        wf.week = date.Substring(10);
        wf.high_1 = nodes[1].InnerText.Replace("℃","");
        wf.low_1= nodes[2].InnerText.Replace("℃", "");
        wf.type_1 = nodes[3].InnerText.Trim();
        wf.fx_1 = nodes[4].InnerText.Trim();
        //可以继续写如数据
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值