WebClient , MemoryStream , HtmlDocument , HtmlNodeCollection , 爬蟲
class Program
{
static void Main(string[] args)
{
string price92 = ""; //92無鉛價格
string price95 = ""; //95無鉛價格
string price98 = ""; //98無鉛價格
string priceDiesel = ""; //柴油價格
WebClient wc = new WebClient();
MemoryStream ms = new MemoryStream(wc.DownloadData("https://m.gas.goodlife.tw/"));
HtmlDocument hd = new HtmlDocument();
hd.Load(ms, Encoding.Default);
HtmlNodeCollection hnc
= hd.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[2]/div[1]/div[1]/ul[2]/li[2]");
price92 = GetInnerText(hnc) ;
hnc = hd.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[2]/div[1]/div[1]/ul[2]/li[3]");
price95 = GetInnerText(hnc);
hnc = hd.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[2]/div[1]/div[1]/ul[2]/li[4]");
price98 = GetInnerText(hnc);
hnc = hd.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[2]/div[1]/div[1]/ul[2]/li[5]");
priceDiesel = GetInnerText(hnc) ;
}
public string GetInnerText(HtmlNodeCollection hnc) //Html字串處理
{
return hnc[0].InnerHtml.Replace("\n", "").Replace(" ", "").Replace("<h3>", "").Replace("</h3>", "").Trim().Split(':')[1];
}
}
該油價網站的html結構,參考下圖: