# 收集Google Trend關鍵字熱度 > #### 並將結果儲存到Excel檔案後繪製成折線圖 ![](https://hackmd.io/_uploads/ry-JjdHza.png) #### !!! 注意 !!! 因為關鍵字熱度Google Trend有非常嚴格的存取次數限制,而該限制目前不明,因此建議盡可能完成程式功能後再進行執行程式。 如果遇到錯誤代碼:429,即表示因為超過次數被Google Trend封鎖了,此時可以嘗試切換`geo`參數,例如: ```python= pytrend.build_payload(kw_list=[keyword], cat=0, timeframe='today 12-m', geo='TW') ``` 變成: ``` pytrend.build_payload(kw_list=[keyword], cat=0, timeframe='today 12-m', geo='JP') ``` >geo code清單(ISO-3166 alpha 2欄位):https://www.geonames.org/countries/ ## 需安裝的模組 | 模組名稱 | 安裝指令 | 說明 | | -------- | ----------------------- | ---------------- | | openpyxl | `pip3 install openpyxl` | Excel模組 | | pytrends | `pip3 install pytrends` | Google Trend模組 | #### 官方文件 pytrends: https://pypi.org/project/pytrends/#installation openpyxl: https://openpyxl.readthedocs.io/en/stable/tutorial.html ## 常見例外 1. `pytrends.exceptions.TooManyRequestsError: The request failed: Google returned a response with code 429` ##### 說明 因為太頻繁用程式存取,被Google Trend網站擋住了。 2. `pytrends.exceptions.ResponseError: The request failed: Google returned a response with code 400` ##### 說明 呼叫Google Trend時,傳遞了錯誤的參數格式。 ## 程式碼說明 ``` pytrend.build_payload(kw_list=[keyword], cat=0, timeframe='today 12-m') ``` ##### 說明: 設定Google Trend參數 ##### 參數: ###### kw_list 要搜尋關鍵字清單,資料類型為list,可以輸入多個關鍵字 ###### cat 要搜尋的類別 > 所有類別代號:https://github.com/pat310/google-trends-api/wiki/Google-Trends-Categories ###### geo 國家代碼,如果沒有提供則表示:全球 > geo code清單(ISO-3166 alpha 2欄位):https://www.geonames.org/countries/ ###### timeframe 要取得資料的日期區間: - Defaults to last 5yrs, `'today 5-y'`. - Everything `'all'` - Specific dates, 'YYYY-MM-DD YYYY-MM-DD' example `'2016-12-14 2017-01-25'` - Specific datetimes, 'YYYY-MM-DDTHH YYYY-MM-DDTHH' example `'2017-02-06T10 2017-02-12T07'` - Note Time component is based off UTC - Current Time Minus Time Pattern: - By Month: `'today #-m'` where # is the number of months from that date to pull data for - For example: `'today 3-m'` would get data from today to 3months ago - **NOTE** Google uses UTC date as *'today'* - **Works for 1, 3, 12 months only!** - Daily: `'now #-d'` where # is the number of days from that date to pull data for - For example: `'now 7-d'` would get data from the last week - **Works for 1, 7 days only!** - Hourly: `'now #-H'` where # is the number of hours from that date to pull data for - For example: `'now 1-H'` would get data from the last hour - **Works for 1, 4 hours only!** ```python= data = pytrend.interest_over_time() ``` ##### 說明: 取得指定時間內被搜尋的次數,回傳為Pandas的DataFrame物件 ## 完整程式碼 ```python= from pytrends.request import TrendReq import openpyxl from openpyxl.chart import LineChart, Reference import time # 根據時間產生檔名 def get_current_date_str(): now = time.localtime() # 取得目前本地時間 return time.strftime('%Y%m%d') # 格式化後的時間字串 def google_trend_explorer(keyword): # 建立Google Trend Request物件 pytrend = TrendReq() # 設定Google Trend參數 pytrend.build_payload(kw_list=[keyword, 'aaron', 'home'], cat=0, timeframe='today 12-m', geo='TW') # 取得指定時間內被搜尋的次數,回傳為Pandas的DataFrame物件 data = pytrend.interest_over_time() # data = data.reset_index() print(data) # 取得目前時間字串 now_str = get_current_date_str() # 將index欄位也寫入excel中 data.to_excel(f'google-trend-temp-{now_str}.xlsx', sheet_name='ChatGPT', index=True) # 呼叫建立Google Trend關鍵字Excel折線圖函式 make_line_chart(now_str) # 建立建立Google Trend關鍵字Excel折線圖函式 def make_line_chart(now_str): # 讀取excel檔 wb = openpyxl.load_workbook(f'google-trend-temp-{now_str}.xlsx') # 取得目前的工作表 ws = wb.active # 建立折線圖物件 chart = LineChart() # 資料來源(row必須填1, 因為下面一行會把第一筆row當成標題) data = Reference(ws, min_col=2, max_col=ws.max_column - 1, min_row=1, max_row=ws.max_row) # 資料加入圖表 chart.add_data(data, titles_from_data=True) # 圖表標題 chart.title = 'Google Trend' # X軸標題 # chart.x_axis.title = '時間' # 設定圖表x軸的日期格式 chart.x_axis.number_format ='yyyy/mm/dd' # Y軸標題 chart.y_axis.title = '資料筆數' # 建立X軸資料標籤 xlabels = Reference(ws, min_col=1, min_row=2, max_row=ws.max_row) # 設定X軸標籤 chart.set_categories(xlabels) # 設定圖表大小,預設15x10公分 chart.width = 15 # 單位: 公分 chart.height = 10 # 單位: 公分 # 修改樣式 chart.style = 30 # 將圖表放在E2位置 ws.add_chart(chart, 'E2') # 存擋為Excel wb.save(f'google-trend-chart-{now_str}.xlsx') ```