利用 PHP 正則表達式從淘寶商品頁面 HTML 中提取價格,可應用於比價系統、價格監控、自動錄入等場景。本文提供一個開箱即用的函數 taoBaoJiaGe(),僅需傳入商品鏈接即可返回當前價格。
<?php
/**
* 獲取淘寶商品頁面價格
* @param string $url 淘寶/天貓商品鏈接
* @return string|false 價格字符串(如 "199.00"),失敗返回 false
*/
function taoBaoJiaGe($url)
{
// 1. 獲取頁面 HTML(建議設置 User-Agent 和超時)
$context = stream_context_create(array(
'http' => array(
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'timeout' => 10,
)
));
$html = @file_get_contents($url, false, $context);
if ($html === false) {
return false;
}
// 2. 第一次正則:定位包含價格的標籤(id="J_StrPrice" 或類似)
// 注意:淘寶頁面結構可能變動,需定期驗證選擇器
if (!preg_match('/<strong\s+id=["\']J_StrPrice["\']\s*>\s*([\d,]+\.\d{2})/i', $html, $match)) {
// 兼容其他常見價格容器
if (!preg_match('/<span\s+class=["\']price[^"\']*["\']\s*>\s*([\d,]+\.\d{2})/i', $html, $match)) {
return false;
}
}
// 3. 第二次正則:從匹配結果中純提取數字價格
$priceStr = $match[1]; // 已捕獲組
// 移除可能的千分位逗號
$priceStr = str_replace(',', '', $priceStr);
// 4. 簡單驗證格式
if (!preg_match('/^\d+\.\d{2}$/', $priceStr)) {
return false;
}
return $priceStr;
}
// --- 使用示例 ---
$itemUrl = 'https://item.taobao.com/item.htm?id=1234567890'; // 替換為真實商品鏈接
$price = taoBaoJiaGe($itemUrl);
if ($price !== false) {
echo "當前價格:¥ " . $price;
} else {
echo "價格獲取失敗,可能頁面結構變更或請求被攔截。";
}
?>
file_get_contents 返回原始編碼,正則匹配時建議在單字節模式下操作或先 iconv('GBK', 'UTF-8', $html) 轉碼。爬蟲采集需遵守 robots.txt、網站服務條款、《網絡安全法》及《數據安全法》。商業用途應申請官方授權接口,切勿高頻請求影響平台正常運營,切勿采集用戶隱私數據。本代碼僅供技術學習與個人非商業研究使用。
掌握正則提取價格技巧,結合緩存、代理、API 多重策略,可構建穩健的電商價格監控體系。