2024-05-22|閱讀時間 ‧ 約 25 分鐘

使用 Python 取得 Google 趨勢的熱門關鍵詞

在這篇教學文章中,我們將展示如何使用 Python 和 pytrends 套件來取得 Google 趨勢(Google Trends)的熱門關鍵詞。我們會詳細說明如何安裝和設定 pytrends,並提供範例程式碼來幫助你輕鬆獲取台灣地區的熱門搜尋趨勢。

前置準備

在開始之前,你需要確保已經安裝了 Python 環境,並且已經安裝了 pytrends 套件。你可以在命令列或終端機中執行以下指令來安裝 pytrends

pip install pytrends

導入所需模組

首先,我們需要導入 pytrends 和 Python 的日期時間模組:

from pytrends.request import TrendReq
from datetime import datetime, timedelta

設定 Google 趨勢的請求

接下來,我們需要設定與 Google 趨勢的連線。這裡我們使用繁體中文介面,並設定時區為 UTC+8(台灣標準時間):

pytrends = TrendReq(hl='zh-TW', tz=360)

設定要取得的時間範圍

我們計算昨天的日期,並將其格式化為 Google 趨勢所需要的時間範圍格式:

today = datetime.today()
yesterday = today - timedelta(days=1)
timeframe = f'{yesterday.strftime("%Y-%m-%d")} {today.strftime("%Y-%m-%d")}'

取得熱門關鍵詞

接下來,我們使用 pytrends 提供的方法來取得台灣的熱門搜尋關鍵詞。有兩種方法可以取得這些資料:

1. 每日趨勢搜尋(Daily Search Trends)

這個方法可以取得每日的熱門關鍵詞:

trending_searches_df = pytrends.trending_searches(pn='taiwan')

# 顯示結果
print(trending_searches_df)

2. 實時趨勢搜尋(Real-time Search Trends)

這個方法可以取得實時的熱門關鍵詞:

python複製程式碼trending_searches_df = pytrends.realtime_trending_searches(pn='TW')

# 顯示前10個結果
print(trending_searches_df.head(10))

完整範例程式碼

以下是完整的範例程式碼,展示如何使用上述方法來取得台灣的熱門搜尋趨勢:

from pytrends.request import TrendReq
from datetime import datetime, timedelta

# 設定 Google 趨勢的請求
pytrends = TrendReq(hl='zh-TW', tz=360)

# 設定要取得的時間範圍
today = datetime.today()
yesterday = today - timedelta(days=1)
timeframe = f'{yesterday.strftime("%Y-%m-%d")} {today.strftime("%Y-%m-%d")}'

# 取得台灣的每日熱門關鍵詞
daily_trending_searches_df = pytrends.trending_searches(pn='taiwan')
print("每日趨勢搜尋:")
print(daily_trending_searches_df)

# 取得台灣的實時熱門關鍵詞
realtime_trending_searches_df = pytrends.realtime_trending_searches(pn='TW')
print("實時趨勢搜尋:")
print(realtime_trending_searches_df.head(10))

結論

通過這篇教學文章,我們學會了如何使用 Python 和 pytrends 來取得 Google 趨勢的熱門關鍵詞。這些資料可以用來進行進一步的分析和研究,幫助我們了解最新的搜尋趨勢。如果你有任何問題或需要進一步的幫助,歡迎在下方留言。

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.