采集接口或页面时,经典 ASP 最常用的客户端是 MSXML2.XMLHTTP。它返回的 ResponseBody 是二进制字节数组,直接转成字符串会乱码,需要借助 ADODB.Stream 按源站字符集转码。
实现思路
FetchBytes 负责发请求拿字节;BytesToText 先把字节写入二进制流,再切换为文本模式并指定 Charset 读出字符串。charset 参数按目标站声明传 gb2312 或 utf-8。
完整代码
<%@ Language="VBScript" CodePage=65001 %>
<%
Option Explicit
Rem 抓取远程页面字节
Function FetchBytes(url)
Dim http
Set http = Server.CreateObject("MSXML2.XMLHTTP")
http.Open "GET", url, False
http.Send
FetchBytes = http.ResponseBody
Set http = Nothing
End Function
Rem 字节数组按指定字符集转文本
Function BytesToText(bytes, charset)
Dim stream
Set stream = Server.CreateObject("ADODB.Stream")
stream.Type = 1
stream.Open
stream.Write bytes
stream.Position = 0
stream.Type = 2
stream.Charset = charset
BytesToText = stream.ReadText
stream.Close
Set stream = Nothing
End Function
Dim html
html = BytesToText(FetchBytes("https://example.com/page.htm"), "gb2312")
Response.Write Server.HTMLEncode(Left(html, 500))
%>注意
- 同步请求设 False,页面会阻塞等待返回,超时控制建议在 HTTP 对象上用 SetTimeouts;
- 对方编码不确定时,可先看响应头 Content-Type 里的 charset 再决定转码参数;
- 采集务必遵守对方 robots 与频率限制,控制访问量。
小结
XMLHTTP 加 Stream 转码是经典 ASP 抓取的黄金组合,拿到 utf-8 的 ResponseText 再处理正则或 XML 解析都会顺畅很多。
评论(0)
暂无评论,快来抢沙发吧~