office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

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

VB及VBA获取网页内容、下载进度条及乱码问题解决

2017-09-18 21:45:00
网络未知
转贴
6182
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
分享