1: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
2:
3: Dim sHtml As String
4: Dim request As System.Net.WebRequest = System.Net.WebRequest.Create("http://www.weather.gov.hk/textonly/forecast/englishwx.htm")
5: ' 要抓取該日天氣資料的天文台網頁.
6:
7: request.Credentials = System.Net.CredentialCache.DefaultCredentials
8: ' 憑據確認.
9:
10: Try
11: Dim response As System.Net.HttpWebResponse = CType(request.GetResponse(), System.Net.HttpWebResponse)
12:
13: ' 回應確認有權取得該天文台網頁上的HTML程式碼.
14: Console.WriteLine(response.StatusDescription)
15:
16: ' 透過streamReader去存取該天文台網頁上的HTML程式碼
17: Dim dataStream As System.IO.Stream = response.GetResponseStream()
18: Dim sr As New System.IO.StreamReader(dataStream)
19:
20: sHtml = sr.ReadToEnd()
21: dataStream.Close()
22: response.Close()
23:
24: If sHtml <> "" Then
25: '把抓取到的該日天氣資料拆開成陣列
26: Dim WeatherParam As String() = sHtml.Split(vbCrLf)
27:
28: '抓取該日的氣溫
29: LblTemperature.Text = WeatherParam(12)
30:
31: '抓取該日天氣的濕度值
32: LblHumidity.Text = WeatherParam(13)
33:
34: '抓取該日天氣縮圖
35: LblWeatherCartoon.Text = WeatherParam(14)
36:
37: '抓取該日天氣的Intensity
38: LblIntensity.Text = WeatherParam(17)
39: Else
40: LblTemperature.Text = "網頁無法正常顯示."
41: End If
42:
43: Catch ex As Exception
44: LblTemperature.Text = ex.Message
45:
46: End Try
47: End Sub
以下是的程式碼是把對應的天氣資料值顯示到網頁介面上
1: <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4:
5: <html xmlns="http://www.w3.org/1999/xhtml">
6: <head runat="server">
7: </head>
8: <body>
9:
10: <form id="form1" runat="server">
11: <asp:Label ID="LblTemperature" runat="server" Text=""></asp:Label>
12: <br />
13: <asp:Label ID="LblHumidity" runat="server" Text=""></asp:Label>
14: <br />
15: <asp:Label ID="LblWeatherCartoon" runat="server" Text=""></asp:Label>
16: <br />
17: <asp:Label ID="LblIntensity" runat="server" Text=""></asp:Label>
18: </form>
19:
20: </body>
21: </html>
*因為香港天文台會不定期修改網頁上的資料,請因應HTML程式碼的改變,自行修改。
沒有留言:
張貼留言