本文详解如何绕过前端渲染限制,利用 Chrome DevTools Protocol 捕获后台 API 响应,从 Maroof.sa 的 /businesses 页面动态提取所有商户详情链接(如 /details/{id}),并提供可运行的反反爬增强版 Selenium 脚本。
本文详解如何绕过前端渲染限制,利用 chrome devtools protocol 捕获后台 api 响应,从 maroof.sa 的 `/businesses` 页面动态提取所有商户详情链接(如 `/details/{id}`),并提供可运行的反反爬增强版 selenium 脚本。
Maroof.sa 的商户列表页(https://maroof.sa/businesses)采用典型的 SPA 架构:页面初始 HTML 中不包含真实跳转链接,所有商户卡片(如 “Marwa Store”)仅渲染静态信息,而实际详情页 URL 需通过 AJAX 请求动态生成。直接解析 DOM(如 div.storeCard)无法获取链接——因为 href 属性根本不存在于源码中。真正的链接藏在后台接口 https://maroof.sa/api/business/search 的 JSON 响应中,其结构为 { "items": [ { "id": "12345", ... } ] },详情页 URL 可由固定模板拼接:https://maroof.sa/details/{id}。
因此,核心思路是:捕获浏览器发出的 business/search 网络请求,解析其响应体,提取 items[].id 并构造完整链接。Selenium 4+ 支持 Chrome DevTools Protocol(CDP),可通过 driver.get_log("performance") 获取性能日志,再筛选出目标请求的 requestId,最后调用 Network.getResponseBody 获取原始 JSON 数据。
以下是经过实战优化的完整解决方案(含反反爬关键配置):
import json
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 启用性能日志并配置反检测选项
options = Options()
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
options.add_argument("--no-sandbox")
options.add_argument("--disable-gpu")
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--enable-javascript")
options.add_argument("--enable-cookies")
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches", ["enable-automation"])
# 隐藏 window.navigator.webdriver 标志(关键!)
options.add_argument("--disable-blink-features")
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options)
url = "https://maroof.sa/businesses"
driver.get(url)
# 等待页面加载及 API 请求完成(建议加显式等待更健壮)
time.sleep(8) # 实际项目中建议用 WebDriverWait 等待特定元素或网络空闲
# 提取性能日志
logs = driver.get_log("performance")
def extract_business_links():
target_api = "business/search"
links = []
for log in logs:
try:
message = json.loads(log["message"])["message"]
if "Network.responseReceived" not in message:
continue
params = message.get("params", {})
response = params.get("response", {})
if not response or target_api not in response.get("url", ""):
continue
# 获取响应体
body = driver.execute_cdp_cmd(
'Network.getResponseBody',
{'requestId': params["requestId"]}
)
data = json.loads(body['body'])
for item in data.get("items", []):
link = f"{url}/details/{item['id']}"
links.append(link)
print(link)
except (json.JSONDecodeError, KeyError, Exception) as e:
continue # 跳过异常日志项,避免中断
return links
all_links = extract_business_links()
print(f"\n✅ 成功提取 {len(all_links)} 个商户详情链接")
driver.quit()
⚠️ 重要注意事项:
- 反爬强度高:Maroof.sa 使用了强效 Bot 检测(甚至人工访问也偶发拦截),上述 stealth 选项仅能提升成功率,强烈建议搭配高质量住宅代理(Residential Proxy)使用;
- 请求时机敏感:get_log("performance") 必须在 API 请求完成后调用,time.sleep(8) 是保守值,生产环境应监听 Network.loadingFinished 或等待特定 DOM 元素出现;
- API 响应结构可能变更:定期检查 /api/business/search 返回的 JSON 字段(如 items → data),及时调整解析逻辑;
- 法律与合规:请务必查阅 Maroof.sa 的 robots.txt 和服务条款,确保抓取行为符合其允许范围,建议添加合理请求间隔并尊重 Rate-Limit 头。
该方法不依赖可见 DOM,直击数据源头,稳定性和可维护性远超模拟点击或滚动触发加载的方案,是处理现代 JS 渲染网站动态链接提取的推荐实践。











