萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 抓取遠端網頁內容:MSXML2.ServerXMLHTTP + 編碼自動偵測與轉換

核心元件

MSXML2.ServerXMLHTTP(或 3.0/6.0 版本)為伺服器端 HTTP 客戶端,支援同步請求、逾時設定、HTTPS、Proxy 等,適合爬蟲、API 串接、內容聚合。

完整抓取與編碼轉換代碼

<%
Function GetRemoteContent(url)
  Dim http, resText, resBody, charset, bodyStr
  
  Set http = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
  ' 設定逾時(毫秒):resolve, connect, send, receive
  http.setTimeouts 10000, 10000, 10000, 10000
  
  On Error Resume Next
  http.Open "GET", url, False
  http.Send
  On Error GoTo 0
  
  If Err.Number <> 0 Then
    GetRemoteContent = "請求失敗: " & Err.Description
    Exit Function
  End If
  
  If http.Status <> 200 Then
    GetRemoteContent = "HTTP 錯誤: " & http.Status & " " & http.StatusText
    Exit Function
  End If
  
  ' 取得原始位元組陣列
  resBody = http.ResponseBody
  
  ' 從 HTML meta 標籤或 HTTP 標頭偵測編碼
  resText = http.ResponseText ' MSXML 嘗試依標頭解碼,可能錯誤
  charset = DetectCharset(resText, http.GetResponseHeader("Content-Type"))
  
  ' 使用 ADODB.Stream 正確轉碼
  GetRemoteContent = BytesToStr(resBody, charset)
End Function

' 偵測編碼:優先 HTTP 標頭,其次 HTML meta charset
Function DetectCharset(html, contentTypeHeader)
  Dim re, matches, charset
  charset = "utf-8" ' 預設
  
  ' 1. 解析 Content-Type 標頭
  If contentTypeHeader <> "" Then
    Set re = New RegExp
    re.IgnoreCase = True
    re.Pattern = "charset\s*=\s*([\w-]+)"
    Set matches = re.Execute(contentTypeHeader)
    If matches.Count > 0 Then charset = matches(0).SubMatches(0)
  End If
  
  ' 2. 解析 HTML meta
  If charset = "utf-8" Then ' 標頭未指定才解析 HTML
    re.Pattern = "]+charset\s*=\s*[""']?([\w-]+)"
    Set matches = re.Execute(html)
    If matches.Count > 0 Then charset = matches(0).SubMatches(0)
  End If
  
  DetectCharset = LCase(charset)
End Function

' 位元組陣列轉字串 (ADODB.Stream)
Function BytesToStr(bytes, charset)
  Dim stream
  Set stream = Server.CreateObject("ADODB.Stream")
  stream.Type = 1 ' 二進位
  stream.Mode = 3
  stream.Open
  stream.Write bytes
  stream.Position = 0
  stream.Type = 2 ' 文字
  stream.Charset = charset
  BytesToStr = stream.ReadText
  stream.Close
  Set stream = Nothing
End Function
%>

使用範例

<%
Dim url, content
url = "https://example.com/page.asp"
content = GetRemoteContent(url)

If Left(content, 6) = "請求失敗" Or Left(content, 5) = "HTTP 錯誤" Then
  Response.Write "
" & content & "
" Else Response.Write "" End If %>

進階功能擴充

需求實作方式
POST 表單提交http.Open "POST", url, False → http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" → http.Send "key1=val1&key2=val2"
攜帶 Cookiehttp.SetRequestHeader "Cookie", "sessionid=abc123"
設定 User-Agenthttp.SetRequestHeader "User-Agent", "Mozilla/5.0 (compatible; MyBot/1.0)"
使用 Proxyhttp.SetProxy 2, "proxy.example.com:8080", "", "user", "pass"
忽略 SSL 憑證錯誤http.Option(2) = 13056 ' SERVERXMLHTTP_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS

效能與禮儀

  • 快取結果:相同 URL 在短時間內(如 5 分鐘)勿重複抓取,使用 Application 變數或檔案快取。
  • 遵守 robots.txt 與 Crawl-delay。
  • 設定合理 setTimeouts 避免長時間阻塞 ASP 執行緒。
  • 大量抓取請使用專用爬蟲框架(Python Scrapy、Node.js Crawlee),ASP 不適合高併發非同步抓取。

常見問題排查

  • 中文亂碼:確認 DetectCharset 正確偵測,必要時強制指定 charset = "gb2312" 或 "big5"。
  • 頁面為空:目標站可能需 JavaScript 渲染(SPA),ServerXMLHTTP 無法執行 JS。改用 Headless Chrome (Puppeteer/Playwright) 或檢查 API 端點直接呼叫。
  • 403 Forbidden:目標站反爬蟲,需模擬完整瀏覽器 Header、Cookie、指紋。
copyright © 萬盛學電腦網 all rights reserved