不少人使用 XMLHTTP 時,總為中文亂碼所苦。網路上多數解法都仰賴 ASP 伺服器端技術,但其實也可以完全在使用戶端解決。本文示範以 VBScript 用戶端腳本,不使用 ASP 也能解決抓取 HTML 頁面時的中文亂碼問題。
原因很簡單:XMLHTTP 取得 Response 時假定它是 UTF-8 編碼,於是就把含 GB2312 編碼的 HTML 當成 UTF-8 來解析,因此出現中文亂碼。
XMLHTTP 的 responseBody 回傳的是一個 unsigned bytes 陣列。VBScript 提供了許多操作字串、格式化資料以及存取安全陣列的方法,這些在 JScript 中並不存在。這裡我們會用到 VBScript 的內建函式:MidB、AscB、LenB 等來存取 responseBody。
以下程式碼包含取得自身網頁碼與取得其他網頁碼兩種應用:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<script language="VBScript">
Function bytes2BSTR(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn, i, 1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn, i + 1, 1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
bytes2BSTR = strReturn
End Function
Function viewSource1()
dim xmlHttp
set xmlHttp = CreateObject("Microsoft.XMLHTTP")
xmlHttp.Open "GET", document.location.href, false
xmlHttp.setRequestHeader "Content-Type", "text/XML"
xmlHttp.Send
dim html
html = bytes2BSTR(xmlHttp.responseBody)
msgbox html
End Function
Function viewSource2()
dim xmlHttp
set xmlHttp = CreateObject("Microsoft.XMLHTTP")
xmlHttp.Open "GET", "https://www.google.com", false
xmlHttp.setRequestHeader "Content-Type", "text/XML"
xmlHttp.Send
dim html
html = bytes2BSTR(xmlHttp.responseBody)
msgbox html
End Function
</script>
<body bgcolor="gainsboro" style="border:1pt solid white">
<button onclick="viewSource1()">查看自身的網頁代碼</button>
<button onclick="viewSource2()">查看 google 主頁代碼</button>
</body>
</html>
核心在於 bytes2BSTR() 函式:它逐位元組讀取 responseBody,透過位元運算把位元組重組成正確的字元,从而在不動用伺服器端的情況下,正確顯示抓取到的中文內容。