Tải bản đầy đủ - 0 (trang)
Hack 81. Import Yahoo! Local Listings into Excel

Hack 81. Import Yahoo! Local Listings into Excel

Tải bản đầy đủ - 0trang

Unfortunately,Yahoo!Localwon'ttellyouwhichplaceshave

freewirelessaccess,soyou'dhavetocalleachofthe

businessestoaskthem.Youcouldscrollandclickthroughthe

webpageandjotdowneachphonenumber,oryoucouldtake

advantageoftheYahoo!LocalAPItoimportthelistintoa

spreadsheetforquickreferencetothephonenumbers.



5.6.1.ExportingYahoo!LocalSearchtoa

Spreadsheet

ProgrammerRikulPatelhasalreadydonemuchofthework

involvedwithimportingresultsintoaspreadsheet.Hisprogram,

calledYahoo!LocalSearchToExcel,isavailableforfreeat

http://rikulpatel.com/ylocalsearch.php.It'savailableon

Windowsonly,andyou'llneedaspreadsheetprogramsuchas



Exceltoviewtheresults.

Onceyoudownloadtheprogram,there'snothingtoinstall.

Double-clickYLocalSearch.exeandyou'llseeaformliketheone

showninFigure5-10.



Figure5-10.TheYahoo!LocalSearchToExcel

form



Typeinaquery,ZipCode,andradius,andthenclickLocal

Search.Behindthescenes,theprogramasksYahoo!forthe

dataandformatstheresponseasacomma-separatedvalue

(CSV)file.Theprogramwillaskyoutonamethefile,socallit

somethingappropriate,likecorvallis_wifi.csvinthisexample.If

Excelisinstalledonyoursystem,corvallis_wifi.csvshouldopen

inExcelwhenyoudouble-clickit,andyou'llseeaspreadsheet

liketheoneshowninFigure5-11.



Figure5-11.Yahoo!LocalresultsinanExcel

spreadsheet



Thespreadsheetincludesthename,address,city,state,and

phonenumberofthebusiness.IfYahoo!hasawebsitelisted

forthebusiness,that'sincludedaswell.Withthedatainthe

spreadsheet,youcanthenaddyourowncolumns,mixitwith

existingdata,orevencreatechartsbasedonthedata.Andthis

definitelymakesforaquicklistofphonenumbersyoucancall

toseewhohasfreewirelessinthearea.



5.6.2.UsingPerl

Yahoo!LocalSearchToExceliseasytouse,buttheoutputisn't

veryflexible.Toaccesssomeoftheotherdataavailable

throughtheYahoo!APIsuchasdistanceanduserratingsyou'll

needtowriteyourowncode.Luckily,thisisfairlyquickwork

withascriptinglanguagelikePerl.



5.6.2.1.Thecode.

Muchlikethepreviousprogram,thisPerlscriptacceptsaquery

andaZipCodeandassemblesaCSVfilewithresultsfroma

Yahoo!LocalSearch.AswithmostoftheotherPerlexamplesin



thisbook,you'llneedtohaveLWP::SimpleandXML::Simpleinstalled

onyoursystemforrequestingandparsingYahoo!data.You'll

alsoneedtheGetopt::Simplemoduleforhandlingthecommandlineparameters.Savethefollowingcodetoafilecalled

yahoo_excel.pl:

#!/usr/bin/perl

#yahoo_excel.pl

#AcceptsaqueryandzipcodeandreturnsaCSV

#listofresultsyoucanopeninExcel.

#Usage:yahoo_excel.pl-q-z

#

#YoucancreateanAppID,andreadthefulldocumentation

#forYahoo!WebServicesathttp://developer.yahoo.net/

usestrict;

useGetopt::Simpleqw($switch);

useLWP::Simple;

useXML::Simple;

#SetyouruniqueYahoo!ApplicationID

my$appID="insertappID";

#Get/Setthecommandlineoptions

my$options=

{























q=>

{

type=>'=s',

env=>'-',

default=>'',

verbose=>'Specifyaquery',

order=>1,

},

zip=>

{





type=>'=f',



env=>'-',



default=>'',



verbose=>'Specifyazipcode',



order=>2,



},

};

my$option=Getopt::Simple->new();

if(!$option->getOptions($options,





"Usage:yahoo_excel.pl-q[query]-z[zipcode]





exit(-1);

}



#Makesurethecommandlineoptionshavevalues

my$query=$$switch{'q'};

my$zip=$$switch{'zip'};

if((!$query)||(!$zip)){



print"Usage:yahoo_excel.pl-q-z";



exit;

};

#ConstructaYahoo!LocalQuerywithonlyrequiredoptions

my$language="en";

my$req_url="http://api.local.yahoo.com/";

$req_url.="LocalSearchService/V1/localSearch?";

$req_url.="appid=$appID";

$req_url.="&query=$query";

$req_url.="&zip=$zip";

#Maketherequest

my$yahoo_response=get($req_url);

#ParsetheXML

my$xmlsimple=XML::Simple->new();

my$yahoo_xml=$xmlsimple->XMLin($yahoo_response);



#Loopthroughtheitemsreturned,printingasCSV

print"\"Title\",\"Address\",\"Distance\",\"Rating\"\n";

foreachmy$result(@{$yahoo_xml->{Result}}){



my$title=$result->{Title};



my$address=$result->{Address};



my$distance=$result->{Distance};



my$rating=$result->{Rating};



if(!eval($rating)){





$rating="";



}



print"\"$title\",\"$address\",\"$distance\"\,\"$rating

}



Withabitmorecontroloverthefile,youcandecidewhich

columnsyou'dliketoincludeinyourspreadsheet.Asyoucan

seeinthelastlineofthiscode,thescriptprintsthetitleofthe

business,theaddress,thedistancefromthecenteroftheZip

Code,andtheratingasanaverageofYahoo!userratingsfor

thatbusiness.



5.6.2.2.Runningthehack.

Runthecodefromthecommandlinebypassinginthetwo

parameters:-qfollowedbyaquery,and-zfollowedbyaZip

Code.Ifyou'restilllookingforwirelesshotspotsinCorvallis,

youmightcallthescriptlikethis:





perlyahoo_excel.plqwifiz97333



Ifallgoeswell,youshouldseeablockoftextscrollpastwith

alloftheoptions.Becauseyou'dratherreadtheresultsina

spreadsheet,youshouldpipetheresultstoaCSVfile,likeso:



perlyahoo_excel.plqwifiz97333>wifi.csv



Double-clickthenewlycreatedwifi.csvtoseetheresultsofthe

query,andyoushouldhavesomethinglikewhat'sshownin

Figure5-12.



Figure5-12.CustomYahoo!Localresultsinan

Excelspreadsheet



Withacustomscript,youcannowquicklyseenotonlywhich

businessesofferwirelessInternetaccess,butalsohowclose

theyareandhowYahoo!usershaveratedeachbusiness.The

keytothehackisthat,thankstoYahoo!'sopenAPI,youcan

addthesearchresultstootherprogramssuchasExceland

structurethedatainwaysthatareusefultoyou.



Hack82.SpellWordswithYahoo!Images



WebofLetterscombinesYahoo!ImageSearchresultsto

spellasingleword.

TheWebofLettersisaPHPscriptthatusestheYahoo!Image

SearchAPItograbimagesoflettersfromallovertheWebto

spellwords.Theresultsacombinationofphotosand

illustrationsarealwayssurprisingandcanevenlooklikemodern

art.Yousimplytypeawordintoawebform,andthescript

assemblestheimages.

Thekeytothehackistransformingtheuser'swordintothe

properYahoo!query.Whentheuserentershello,thecode

queriesYahoo!ImageSearchforeachletterintheword"letter

h","lettere","letterl",andsooneventuallyspellingthe

completeword,asshowninFigure5-13.



Figure5-13.Theword"hello"assembledfrom

Yahoo!Images



Whenthecharacterisanumber,thequerysyntaxis"number1",

"number2",etc.Whenthecharacterisasymbol,thecodequeries

Yahoo!foritsfullname;thesymbol&becomesampersand.

YoucantryaworkingWebofLettersisathttp://blog.outercourt.com/yahoo/letters.php5.



5.7.1.TheCode

WebofLettersusesPHP5,andyoucanstartbycreatingafile

calledletters.php5.InadditiontoastandardHTMLhead,add

thefollowingcodetoacceptaqueryparameterq:





$q=(isset($_POST['q']))?$_POST['q']:'';



ThenaddthefollowingXHTMLsnippet,whichwillasktheuser

forinput:



Enteranything:






value=""/>







Printthequeryintheinputboxifsomethinghasbeenposted

already,butmakesuretoconvertittoanHTMLattributevalue

usingthetoAttributefunction:

functiontoAttribute($s)

{



$s=toXml($s);



$s=str_replace('"','&"',$s);



return$s;

}

functiontoXml($s)

{



$s=str_replace('&','&',$s);



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 81. Import Yahoo! Local Listings into Excel

Tải bản đầy đủ ngay(0 tr)

×