在寫爬蟲的時候,很多人第一個想法就是:
但其實 Google 搜尋頁面(https://www.google.com)**不開放 API**,也禁止爬蟲直接抓取。這一集我們就來介紹一個「合法、官方、免費」的 Google 搜尋替代方案:Custom Search JSON API!能不能寫程式自動去抓 Google 搜尋結果?
❌ 為什麼不能直接爬 Google 搜尋頁?
- 搜尋結果是動態 JavaScript 生成的,不是靜態 HTML
- robots.txt 明確禁止爬蟲訪問
/search
- 違反使用政策會導致 IP 被封鎖
✅ 替代方案:Google Custom Search JSON API
Google 官方提供的搜尋服務,讓你可以用程式呼叫 API 取得搜尋結果。
🔧 操作步驟詳解:申請金鑰與設定搜尋引擎
步驟 1:建立自訂搜尋引擎(CSE)
- 前往:https://programmablesearchengine.google.com/
- 點「新增」搜尋引擎
- 網站範圍可填
*.edu.tw
或www.python.org
(可選擇搜尋整個網路) - 建立成功後,複製你的搜尋引擎 ID(cx)
步驟 2:申請 API 金鑰
- 前往:https://console.cloud.google.com/
- 建立專案(若已有可略過)
- 啟用 API:「Custom Search JSON API」
- 前往「API 和服務 > 認證」新增 API 金鑰
- 複製金鑰(key)備用
🧪 程式實作:查詢 "Python 爬蟲"
import requests
api_key = "你的API金鑰"
cx = "你的搜尋引擎ID"
query = "python 爬蟲"
url = "https://www.googleapis.com/customsearch/v1"
params = {
"key": api_key,
"cx": cx,
"q": query
}
r = requests.get(url, params=params)
data = r.json()
for item in data.get("items", []):
print("🔗", item["title"], "→", item["link"])
🔽 輸出範例:
🔗 Python網頁爬蟲實戰 → https://example.com/python-crawler
🔗 BeautifulSoup入門 → https://example.com/tutorial
✅ 延伸任務:
📦 儲存結果為 CSV
import pandas as pd
results = [{"標題": item["title"], "連結": item["link"]} for item in data.get("items", [])]
df = pd.DataFrame(results)
df.to_csv("google_results.csv", index=False, encoding="utf-8")
print("已儲存至 google_results.csv")
🧽 過濾特定來源(例如只保留 medium.com)
filtered = [item for item in results if "medium.com" in item["連結"]]
for f in filtered:
print("📝", f["標題"], "→", f["連結"])
📊 關鍵字頻率分析(統計標題中的熱門詞彙)
from collections import Counter
import re
all_titles = " ".join(item["標題"] for item in results)
words = re.findall(r"\w+", all_titles.lower())
common = Counter(words).most_common(10)
print("🔍 最常見關鍵字:")
for word, count in common:
print(f"{word}:{count} 次")
🔽 輸出範例:
🔍 最常見關鍵字:
python:5 次
爬蟲:4 次
教學:2 次
...(其餘略)
🔎 其他搜尋引擎 API 推薦
若你想獲得更多搜尋來源,這些合法 API 也是非常實用的選擇:
🔹 Bing Web Search API(Microsoft)
- 網址:https://learn.microsoft.com/en-us/bing/search-apis/
- 支援多語系搜尋、圖片、影片、新聞等
- 免費額度每日 1000 次查詢(需申請 Azure 金鑰)
✅ 申請流程簡要:
- 前往 https://portal.azure.com/
- 建立一個免費帳戶並登入
- 點選「建立資源 > AI + Machine Learning > Bing Search v7」
- 設定資源名稱與地區後建立服務
- 前往「金鑰與端點」頁面,複製 API 金鑰與 endpoint
✅ 使用範例
import requests
import os
subscription_key = "你的Bing API金鑰"
url = "https://api.bing.microsoft.com/v7.0/search"
headers = {"Ocp-Apim-Subscription-Key": subscription_key}
params = {"q": "Python 爬蟲", "count": 5, "mkt": "zh-TW"}
r = requests.get(url, headers=headers, params=params)
data = r.json()
for item in data.get("webPages", {}).get("value", []):
print("🔗", item["name"], "→", item["url"])
🔽 輸出範例:
🔗 用 Python 撰寫網路爬蟲 → https://example.com/article
🔗 如何用 requests + BeautifulSoup → https://example.com/bs4
🔹 DuckDuckGo Instant Answer API
- 網址:https://duckduckgo.com/api
- 無需申請金鑰,立即可用
- 適合查詢定義與百科型資料,但不是完整搜尋
✅ 使用方式簡單: 直接使用例如:https://api.duckduckgo.com/?q=python&format=json 可用瀏覽器開即可看到結果,也可搭配 requests 使用。
✅ 使用範例
import requests
url = "https://api.duckduckgo.com/"
params = {"q": "python", "format": "json"}
r = requests.get(url, params=params)
data = r.json()
print("📘 定義:", data.get("AbstractText", "無定義"))
🔽 輸出範例:
📘 定義:Python is an interpreted high-level general-purpose programming language.
🔹 SerpAPI
- 網址:https://serpapi.com/
- 可模擬 Google、Bing、Yahoo 搜尋結果
- 提供整理過的 JSON 結構,非常適合開發者使用
- 免費帳號有每日次數限制
✅ 申請流程簡要:
- 前往 https://serpapi.com/signup 註冊帳戶
- 登入後至 Dashboard 複製你的 API Key
✅ 使用範例
import requests
params = {
"engine": "google",
"q": "Python 爬蟲",
"api_key": "你的APIKey",
"hl": "zh-tw"
}
r = requests.get("https://serpapi.com/search", params=params)
data = r.json()
for item in data.get("organic_results", []):
print("🔍", item.get("title"), "→", item.get("link"))
🔽 輸出範例:
🔍 Python爬蟲實戰入門 → https://example.com/start
🔍 使用Python打造自己的小爬蟲 → https://example.com/scrapy
🔽 說明:SerpAPI 支援更多進階功能,如自動點擊、分頁、新聞/圖片搜尋等。
這些 API 各有優劣,選擇時可根據你爬取的內容、語言、預算與資料需求來考量 👍