萬盛學電腦網

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

ASP 經典:Alexa 排名查詢元件實作(XMLHTTP + 正則解析)

背景

早期 ASP(Classic ASP)無原生 HTTP 客戶端,需借助 Microsoft.XMLHTTP (MSXML) 元件遠程抓取 Alexa 數據,再以正則提取排名。現代開發建議改用 PHP cURL、Python requests 或官方 API。

核心流程

  1. 接收查詢域名參數 d。
  2. 構造 Alexa 數據 API URL:https://data.alexa.com/data/?cli=10&dat=snba&ver=7.0&url= + 域名。
  3. 使用 Server.CreateObject("Microsoft.XMLHTTP") 同步 GET 請求。
  4. 回應為 XML 格式,以 ADODB.Stream 將二進制轉字串(指定 GB2312 編碼)。
  5. 用 RegExp 提取 <REACH RANK="..."> 節點內容。
  6. 輸出超連結指向 Alexa 官網詳細頁。

關鍵程式碼片段

遠程抓取函數

Function getHTTPPage(Path)
    t = GetBody(Path)
    getHTTPPage = BytesToBstr(t, "GB2312")
End Function

Function GetBody(url)
    Set Retrieval = CreateObject("Microsoft.XMLHTTP")
    Retrieval.Open "GET", url, False
    Retrieval.Send
    GetBody = Retrieval.ResponseBody
    Set Retrieval = Nothing
End Function

Function BytesToBstr(body, Cset)
    Dim objstream
    Set objstream = Server.CreateObject("ADODB.Stream")
    objstream.Type = 1 ' 二進制
    objstream.Mode = 3
    objstream.Open
    objstream.Write body
    objstream.Position = 0
    objstream.Type = 2 ' 文本
    objstream.Charset = Cset
    BytesToBstr = objstream.ReadText
    objstream.Close
    Set objstream = Nothing
End Function

正則提取排名

Set reg = New RegExp
reg.Multiline = True
reg.Global = False
reg.IgnoreCase = True
reg.Pattern = "<REACH RANK=((.|\n)*?)>"
Set matches = reg.Execute(wstr)
For Each match1 In matches
    bodypage = del(match1.Value) ' 移除標籤屬性
Next

Function del(str)
    str = Replace(str, "<REACH RANK=""", "")
    str = Replace(str, """ />", "")
    str = Replace(str, " ", "")
    del = str
End Function

現代 PHP 替代實作

<?php
function getAlexaRank($domain) {
    $url = "https://data.alexa.com/data/?cli=10&dat=snba&ver=7.0&url=" . urlencode($domain);
    $xml = @simplexml_load_file($url);
    if ($xml && isset($xml->SD->POPULARITY)) {
        return (int)$xml->SD->POPULARITY['TEXT']; // 文字排名
    }
    return null;
}

echo getAlexaRank("111cn.net");

遷移建議

  • Alexa 官方 API 於 2022/05/01 停止服務,歷史數據不可用。
  • 替代方案:SimilarWeb API、Semrush API、自建爬蟲估算流量。
  • 若維護舊 ASP 系統,確保伺服器安裝 MSXML 3.0+(msxml3.dll),並開啟 Server.ScriptTimeout 防超時。
copyright © 萬盛學電腦網 all rights reserved