爬蟲遇到「搜尋框輸入 → 點擊按鈕 → 獲取結果」流程,核心難點在於**如何將關鍵字寫入 `` 並觸發提交**。視網頁技術棧選擇方案:
// Puppeteer 範例
const page = await browser.newPage();
await page.goto('https://example.com/search');
await page.type('#search-input', '關鍵字', {delay: 50}); // 模擬人類輸入
await page.click('#search-btn');
await page.waitForNavigation(); // 等待結果頁載入
const html = await page.content();
// 解析 html...
import requests
resp = requests.post('https://example.com/api/search',
headers={'User-Agent': '...', 'Cookie': '...', 'Content-Type': 'application/json'},
json={'keyword': '關鍵字', 'page': 1})
data = resp.json()
// 在瀏覽器 Console 或 Selenium execute_script
document.getElementById('search-input').value = '關鍵字';
// 手動觸發事件,否則 Vue/React 雙向綁定不更新
document.getElementById('search-input').dispatchEvent(new Event('input', {bubbles: true}));
document.getElementById('search-form').submit();
| 場景 | 推薦 |
|---|---|
| SPA (Vue/React/Angular)、複雜反爬、需登入態 | Playwright (速度比 Puppeteer 快、API 更現代) |
| 傳統表單提交、介面固定、無加密 | Requests / HttpClient 直呼 API |
| 一次性腳本、頁面極簡、無 JS | Selenium `execute_script` 注入 DOM |
核心心法:**能用 API 就別用瀏覽器,能用瀏覽器就別手工注入 DOM。**