office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

VB及VBA穫取網頁內容、下載進度條及亂碼問題解決

2017-09-18 21:45:00
網絡未知
轉貼
6142
VB及VBA穫取網頁內容、下載進度條及亂碼問題解決

在用vb做“天氣預報自動更新繫統”的時候,需要從中 國氣象網、百度天氣搜索等網站提取天氣信息,因而對用vb提取網頁內容進行瞭一番研究,重點在於解決亂碼問題和字符串提取。
1.下麵是一箇利用INET控件穫取網頁內容以及顯示進度條的例子。
Private Sub Command1_Click()
Dim strURL As String, m_lDocSize As Long, strBuffer As String
Dim lngArrivedDataSize As Long, strArrivedData As String
strURL = “http://zhidao.baidu.com/question/68055519.html”
Inet1.Execute strURL, “GET” ‘髮齣請求
Do While Inet1.StillExecuting ‘等待請求結束
DoEvents
Loop
If Len(Inet1.GetHeader(“Content-Length”)) > 0 Then ‘穫取文件頭信息
m_lDocSize = CLng(Inet1.GetHeader(“Content-Length”))
End If
With ProgressBar1 ‘初始化進度條
.Max = m_lDocSize – Len(Inet1.GetHeader)
.Min = 0
Do  ‘開始穫取數據
DoEvents
strBuffer = Inet1.GetChunk(512)
strArrivedData = strArrivedData & strBuffer
lngArrivedDataSize = Len(strArrivedData)
.Value = lngArrivedDataSize ‘進度顯示
Loop Until Len(strBuffer) = 0
.Value = .Max
End With
MsgBox “下載完畢!”
End Sub
2.下麵是一箇用xmlhttp穫取網頁,能夠解決一些亂碼問題
Private Sub Command1_Click()
Dim a As String
a = RichTextBox1.Text
RichTextBox1.Text = GetBody(a)
End Sub
Public Function GetBody(ByVal URL$, Optional ByVal Coding$ = “GB2312″)
Dim ObjXML
On Error Resume Next
Set ObjXML = CreateObject(“Microsoft.XMLHTTP”)
With ObjXML
.Open “Get”, URL, False, “”, “”
.setRequestHeader “If-Modified-Since”, “0″
.SEnd
GetBody = .ResponseBody
End With
GetBody = BytesToBstr(GetBody, Coding)
Set ObjXML = Nothing
End Function
Public Function BytesToBstr(strBody, CodeBase)
Dim ObjStream
Set ObjStream = CreateObject(“Adodb.Stream”)
With ObjStream
.Type = 1
.Mode = 3
.Open
.Write strBody
.Position = 0
.Type = 2
.Charset = CodeBase
BytesToBstr = .ReadText
.Close
End With
Set ObjStream = Nothing
End Function
分享