概述

Google Trends提供了關於搜尋趨勢與關鍵字熱門程度的寶貴洞察。然而,Google並未提供存取此資料的官方API。幸好,Pytrends程式庫讓我們能夠使用Python存取Google Trends資料。

在本教學中,我們將逐步引導您完成Pytrends的安裝與設定,並示範如何執行簡單的搜尋及解讀結果。

前置條件

若要跟著本教學操作,您應具備:

  • 已安裝Python 3
  • 具備Python程式設計的基礎知識
  • 熟悉Python套件的使用

安裝

若要安裝Pytrends,只需使用pip:

pip install pytrends

設定Pytrends

若要開始使用Pytrends,請先匯入必要的程式庫,並建立與Google Trends的連線:

from pytrends.request import TrendReq

pytrends = TrendReq(hl='en-US', tz=360)

在這裡,我們將語言設定為英文(hl='en-US'),時區設定為UTC+0(tz=360)。

執行基本搜尋

現在,讓我們執行一個簡單的搜尋,查看關鍵字「Python」隨時間的搜尋興趣變化:

keywords = ['Python']
pytrends.build_payload(keywords, timeframe='today 5-y', geo='', gprop='')

interest_over_time_df = pytrends.interest_over_time()
print(interest_over_time_df)

這段程式碼定義了一個關鍵字清單,將時間範圍設定為過去五年(timeframe='today 5-y'),並將地理位置和Google屬性留空。interest_over_time()方法會回傳一個包含興趣資料的DataFrame。

理解結果

回傳的DataFrame包含關鍵字「Python」在過去五年的搜尋興趣資料。這些數值代表相對於指定時間範圍內最高點的搜尋興趣,100代表熱門程度的最高峰。

結論

在本文中,我們介紹了Pytrends——一個非官方的Python版Google Trends API,並示範了如何安裝和設定它。我們使用該程式庫執行了基本搜尋,並討論了如何解讀結果。

在接下來的文章中,我們將深入探討更進階的Pytrends功能,例如分析隨時間變化的興趣、依地區探索興趣,以及發現相關主題與查詢。敬請期待!


NOTE : pytrends uses an unofficial API. Please use here for issues.

SAMPLE CODE : https://github.com/hobbyworker/google-trend-for-python