How to Use Google Trends API with Python | HackerNoon

文章推薦指數: 80 %
投票人數:10人

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!



請為這篇文章評分?