類型: C#學習筆記
目的: 尋找網頁中的特定字串.
參考資料:
MSDN Get HTML code from a website C#
說明讓上一個
滙率程式在使用上更便利, 將網路上匯率資料直接帶進來程式中, 使用者則不需要每次進入程式時, 還需要去其它網頁查看匯率.
這個範例選擇的是
Yahoo換算匯率網頁. 而我需要的資料是下圖紅框中的匯率29.968帶入程式.
程式碼
//將要取得HTML原如碼的網頁放在WebRequest.Create(@”網址” )
WebRequest myRequest = WebRequest.Create(@"http://tw.money.yahoo.com/currency_exc_result?amt=1&from=USD&to=TWD");
//Method選擇GET
myRequest.Method= "GET";
//取得WebRequest的回覆
WebResponse myResponse =myRequest.GetResponse();
//Streamreader讀取回覆
StreamReader sr = new StreamReader(myResponse.GetResponseStream());
//將全文轉成string
string result =sr.ReadToEnd();
//關掉StreamReader
sr.Close();
//關掉WebResponse
myResponse.Close();
//搜尋頭尾關鍵字, 搜尋方法見後記(1)
int first =result.IndexOf("美元 = <em>");
int last =result.LastIndexOf("</em> 新台幣");
//減去頭尾不要的字元或數字, 並將結果轉為string. 計算方式見後記(2)
string HTMLCut =result.Substring(first + 9, last - first - 9);
txtRate.Text = HTMLCut;
後記(1) 取得網頁原始碼比較容易的方法(Firefox舉例)
先將想要的資料反白
點選右鍵 > 檢視選取範圍原始碼
開啓原始碼頁面, 被選取的範圍也會是反白效果呈現
(2) 如何計算
假設以下字串, 你所想要的資料為1234
"AAAAA1234BBBB"
則搜尋為. . .
int first =result.IndexOf("AAAAA");
int last =result.LastIndexOf("BBBB");
string HTMLCut =result.Substring(first + 5, last - first - 4);AAAAA的第一個字元為0, 所以要+5, Substring的開頭才會是1234的1.
BBBB的最得一個字則要-4, Substring的結尾才會是1234的4.
PS: 空格也算一格.
在看回程式中的範例則頭+9尾-9就能取得想要的字串了.
string HTMLCut =result.Substring(first + 9, last - first - 9);