How to Use Google Trends API with Python | HackerNoon
文章推薦指數: 80 %
Pytrends is an unofficial Google Trends API that provides different methods to download reports of trending results from google trends. The python package can ... HowtoUseGoogleTrendsAPIwithPythonOctober7th202113,888reads0PytrendsisanunofficialGoogleTrendsAPIthatprovidesdifferentmethodstodownloadreportsoftrendingresultsfromgoogletrends.Thepythonpackagecanhelpyouautomatetheprocessoffetchingdataandgettheresultoverashortperiodoftime.Inthisarticle,wewilllookatfivemethodsthatcanhelpusfetchdatafromGoogleTrendsindifferentways.ThefirstAPImethodisinterest_over_time,thismethodwillreturnhistoricaldataofthesearchedkeywordfromGoogleTrendaccordingtothetimeframeyouhavespecifiedinthebuild_payloadmethod.@davisdavidDavisDavidDataScientist|AIPractitioner|SoftwareDeveloper.Givingtalks,teaching,writing.About@davisdavidTheGoogleTrendswebsiteprovidesananalysisofdifferentsearchresultsfromGoogleSearchbasedonvariouscriteriasuchasregions,time,andlanguage.Asadeveloper,youcanuseGoogleTrendsAPIinpythontogetthesameresultsaspresentedontheGoogleTrendswebsiteviaPytrends.TableofContents:WhatisPytrends?HowtoInstallPytrendsConnecttoGoogleBuildPayloadInterestOverTimeHistoricalHourlyInterestInterestbyRegion'RelatedQueriesKeywordSuggestionWhatisPytrends?PytrendsisanunofficialGoogleTrendsAPIthatprovidesdifferentmethodstodownloadreportsoftrendingresultsfromgoogletrends.Thepythonpackagecanhelpyouautomatetheprocessoffetchingdataandgettheresultoverashortperiodoftime.Inthisarticle,wewilllookatfivemethodsfromgoogletrendsAPIprovidedbyPytrendsthatcanhelpusfetchdatafromGoogleTrendsindifferentways.So,let'sgetstarted!HowtoInstallPytrendsRunthefollowingcommandtoinstallPytrendsonyourmachine.pipinstallpytrendsNote:pytrendsrequirespython3.3+andthefollowingpythonpackagesRequests,lxml,andpandas.ConnecttoGoogle ThefirststepafterinstallationistoconnectPytrendstoGoogleTrendssothatyoucansendarequestandgettheinformationyouneed.YouneedtoimportTrendReqfrompytrendstoinitializetheconnection.#connecttogoogle frompytrends.requestimportTrendReq pytrends=TrendReq(hl='en-US',tz=360) TheTrendReqreceivestwoimportantparameters.hlstandsforhostinglanguageforaccessingGoogleTrends;inthisexample,wesetEnglish.tzstandsfortimezone,inthisexample,weusetheUStimezone(representedinminutes),whichis360.Formoredetailsaboutthetimezone,pleasecheckthefollowinglink.BuildPayloadThebuild_payloadmethodfromPytrendsisusedtobuildalistofkeywordsyouwanttosearchinGoogleTrends.Youcanalsospecifythetimeframetogatherdataandthecategorytoquerythedatafrom.#buildpayload kw_list=["machinelearning"]#listofkeywordstogetdata pytrends.build_payload(kw_list,cat=0,timeframe='today12-m') Forthisexample,wewillsearchtrendsforthe“machinelearning”keyword.Youcanalsoaddmorekeywordsintokw_listasmanyasyouwant.InterestOverTimeThefirstAPImethodfrompytrendsisinterest_over_time;thismethodwillreturnhistoricaldataofthesearchedkeywordfromGoogleTrendaccordingtothetimeframeyouhavespecifiedinthebuild_payloadmethod.ThenwecanvisualizethedatacollectedbyusingthePlotlylibrarytogetmoreinsightfromthedata.#1InterestoverTime data=pytrends.interest_over_time() data=data.reset_index() importplotly.expressaspx fig=px.line(data,x="date",y=['machinelearning'],title='KeywordWebSearchInterestOverTime') fig.show() Fromtheabovegraph,youcanseethekeyword"machinelearning"hasbeensearchedmostlyfromMarch2021toJuly2021HistoricalHourlyInterestIfyouareinterestedinthehourlyinterestofthekeyword,youcanusetheget_historical_intereset()methodtofetchhourlydataaccordingtothetimeyouhavespecified.pytrends.get_historical_interest(kw_list,year_start=2021,month_start=9,day_start=1,hour_start=0,year_end=2021,month_end=9,day_end=30,hour_end=0,cat=0,sleep=0)Intheabovecode,wehavespecifiedthekeywordswewanttosearch,startingtime,endingtime,andthecategoryofthekeyword.InterestbyRegionSometimesyoucanbeinterestedtoknowtheperformanceofthekeywordperregion.Themethodinterest_by_regionfrompytrendscanshowyouwhichcountriessearchthekeywordyouselectedonascaleof0to100,where100representsacountrywiththemostsearchand0representsacountrythatdoesnothaveenoughdata.by_region=pytrends.interest_by_region(resolution='COUNTRY',inc_low_vol=True,inc_geo_code=False) by_region.head(10) Theresultsarereturnedinadataframeformatbyusingpandas.Youcanalsousepandastofetchcountriesthathaveascoreofgreaterthan10.#byregiongreaterthan10searches by_region[by_region["machinelearning"]>10] RelatedQueriesPytrendscanalsohelpyoufindkeywordsthatarecloselytiedtoaprimarykeywordofyourchoiceandthenreturnalistofrelatedkeywordsshownonGoogleTrends.Letusfindalistofrelatedqueriesfor“machinelearning”andreturnthetopqueries.data=pytrends.related_queries() data['machinelearning']['top'] Asyoucansee,therearedifferentkeywordsthatarerelatedto“machinelearning,”suchas"whatismachinelearning,"and"machinelearningmodel."KeywordSuggestionGoogleTrendscangiveyoualistofkeywordsuggestionsrelatedtoyourprimarykeyword.Intheexamplebelow,youwillsendarequesttofindsuggestionsforakeywordcalled"BusinessIntelligence." ThesuggestionsmethodfrompytrendswillfetchkeywordsuggestionsfromGoogleTrendsandreturntheminadataframeformat.keywords=pytrends.suggestions(keyword='BusinessIntelligence') df=pd.DataFrame(keywords) print(df) Intheabovedataframe,youcanseealistofsuggestedkeywordsfor”BusinessIntelligence,”suchasBusinessIntelligenceSoftware,MarketIntelligence,andothers.ReferenceTherearemoreAPImethodstocoverfromthePytrendspackage;Irecommendyoutakeyourtimetoreadothermethodsinthedocumentation.Checkitouthere.Ifyoulearnedsomethingneworenjoyedreadingthisarticle,pleaseshareitsothatotherscanseeit.Untilthen,seeyouinthenextpost!YoucanalsofindmeonTwitter.Andyoucanreadmorearticleslikethishere.Wanttokeepuptodatewithallthelatestinpython?Subscribetoournewsletterinthefooterbelow.0ClaimyourSEMrushAll-in-oneSEOtoolFREEtrialtodayLOADING...comments&more!
延伸文章資訊
- 1The Ultimate Guide to PyTrends: the Google Trends API (with ...
Google Trends is a public platform that you can use to analyze interest over time for a given top...
- 2[數據分析] 如何利用Google Trend (搜尋趨勢) 挑選爆款商品
利用Python串Google Trend API,拿到過去資料後Pandas合併和整理,再利用Decision Tree、KNN、Logistic Regression...等8種模型進行機器...
- 3Google Trend
顯示第1 個範例,共6 個. 最新報導和深入分析. 探索如何用Google 資料來進行報導。 精選. 2021 年度搜尋排行榜. 透過Google 搜尋趨勢資料的角度,探索今年的搜尋概況。
- 4How to Use Google Trends API with Python | HackerNoon
Pytrends is an unofficial Google Trends API that provides different methods to download reports o...
- 5Google Trends API.ipynb - Colaboratory
Google trends is a website that analyzes and lists the popular search results on Google search ba...