using System.Net;
using System.IO;
using System.Web;
using HtmlAgilityPack;
try
{
//指定來源網頁
WebClient url = new WebClient();
//將網頁來源資料暫存到記憶體內
MemoryStream ms = new MemoryStream(url.DownloadData("http://tw.stock.yahoo.com/q/q?s=" +j.ToString())); //存入一記憶體
//以奇摩股市為例http://tw.stock.yahoo.com
//1101 表示為股票代碼
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); //html文件
// 使用預設編碼讀入 HTML
//HtmlDocument doc = new HtmlDocument();
doc.Load(ms, Encoding.Default); //使用html文件 解析記憶體
// 裝載第一層查詢結果
HtmlAgilityPack.HtmlDocument hdc = new HtmlAgilityPack.HtmlDocument(); //html文件
//XPath 來解讀它 /html[1]/body[1]/center[1]/table[2]/tr[1]/td[1]/table[1]
hdc.LoadHtml(doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/center[1]/table[2]/tr[1]/td[1]/table[1]").InnerHtml); //使用hdc文件去解析特定位置內容
// 取得個股標頭
HtmlNodeCollection htnode = hdc.DocumentNode.SelectNodes("./tr[1]/th"); //個股標頭
// 取得個股數值
string[] txt = hdc.DocumentNode.SelectSingleNode("./tr[2]").InnerText.Trim().Split('\n');
int i = 0;
// 輸出資料
foreach (HtmlNode nodeHeader in htnode)
{
//將 "加到投資組合" 這個字串過濾掉
// Response.Write(nodeHeader.InnerText + ":" + txt[i].Trim().Replace("加到投資組合", "") + "
//");
textBox1.Text += nodeHeader.InnerText + ":" + txt[i].Trim().Replace("加到投資組合", "") + "\r\n";
i++;
}
//清除資料
doc = null;
hdc = null;
url = null;
ms.Close();
}
catch (Exception x)
{
// MessageBox.Show(x.ToString());
}
留言列表