public StockItem getStock(string Num) { try { StockItem stock = new StockItem(); //指定來源網頁 WebClient url = new WebClient(); //將網頁來源資料暫存到記憶體內 MemoryStream ms = new MemoryStream(url.DownloadData("https://tw.stock.yahoo.com/q/q?s=" + Num.ToString())); //以GoogleFinance為範例 // 使用預設編碼讀入 HTML HtmlDocument doc = new HtmlDocument(); HtmlNode tempNode; List <HtmlNode> tdNode; string Text1, Text2; doc.Load(ms, Encoding.GetEncoding("big5")); tempNode = doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]/center[1]/table[2]/tr[1]/td[1]/table[1]/tr[2]"); // 取得股價 stock.Name = tempNode.SelectSingleNode(@"td[1]").InnerText.ToString(); if (stock.Name.IndexOf("加") > 0) { stock.Name = stock.Name.Remove(stock.Name.IndexOf("加")); } stock.Time = tempNode.SelectSingleNode(@"td[2]").InnerText.ToString(); stock.Deal = Decimal.Parse(tempNode.SelectSingleNode(@"td[3]").InnerText.ToString()); if (tempNode.SelectSingleNode(@"td[4]").InnerText.ToString() == "-") { stock.Buy = Decimal.Parse(tempNode.SelectSingleNode(@"td[5]").InnerText.ToString()); } else { stock.Buy = Decimal.Parse(tempNode.SelectSingleNode(@"td[4]").InnerText.ToString()); } if (tempNode.SelectSingleNode(@"td[5]").InnerText.ToString() == "-") { stock.Sell = Decimal.Parse(tempNode.SelectSingleNode(@"td[4]").InnerText.ToString()); } else { stock.Sell = Decimal.Parse(tempNode.SelectSingleNode(@"td[5]").InnerText.ToString()); } tdNode = tempNode.CssSelect("td").ToList(); Text1 = tdNode[5].InnerText.ToString(); Text2 = tdNode[6].InnerText.ToString(); stock.Change = Text1.Remove(Text1.IndexOf(Text2)).Trim(); stock.Volume = int.Parse(tdNode[6].InnerText.ToString().Replace(",", "").Trim()); stock.lastDay = Decimal.Parse(tdNode[7].InnerText.ToString().Trim()); stock.Open = Decimal.Parse(tdNode[8].InnerText.ToString().Trim()); stock.High = Decimal.Parse(tdNode[9].InnerText.ToString().Trim()); stock.Low = Decimal.Parse(tdNode[10].InnerText.ToString().Trim()); //清除資料 doc = null; url = null; ms.Close(); return(stock); } catch (System.IO.IOException e) { logger.Error(LogUtility.GetExceptionDetails(e)); return(null); } }