SlideShare a Scribd company logo
In [ ]:
In [ ]:
# kayak
http://www.kayak.com/flights/SEL-JFK/2015-05-22/2015-05-22
http://www.programmableweb.com/api/kayak
# 개발자 키 다운로드
http://www.kayak.com/labs/api/search
"deprecated"
# minidom 패키지: XML 문서를 객체 트리로 다루는 표준 방법인 DOM인턴페이스의 경량 구현물
>>>import xml.dom.minidom
>>>dom=xml.dom.minidom.parseString('<data><rec>Hello!</rec></data)')
>>>dom
<xml.dom.minidom.Document instance at 0x00980C28>
>>>r=dom.getElementsByTagName('rec')   # getElementsByTagName('rec')
>>>r
[<DOM Element: rec at 0xa42350>]
>>>r[0].firstChild       # firstChild, "Hello"텍스트를 가진 노드
[DOM Text node "Hello!"]
>>>r[0].firstChild.data   # data, 보통 유니코드 문자열
u'Hello!'
# 비행편 검색
# 개발자 키를 사용하여 새로운 카약 세션 얻기
- getkayaksession()
import time
import urllib2
import xml.dom.minidom
kayakkey='YOUR KEY HERE'
def getkayaksession():
# 세션을 시작할 URL을 생성
url='http://www.kayak.com/k/ident/apisession?token=%s&version=1' % kayakkey
# 결과로 나온 XML을 파싱
doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read())
# <sid>xxxxxxxx</sid> 찾기
sid=doc.getElementsByTagName('sid')[0].firstChild.data
return sid
In [ ]:
# 비행편을 검색하는 함수
- flightsearch()
def flightsearch(sid,origin,destination,depart_date):
# 검색 Url을 생성
url='http://www.kayak.com/s/apisearch?basicmode=true&oneway=y&origin=%s' % origin
url+='&destination=%s&depart_date=%s' % (destination,depart_date)
url+='&return_date=none&depart_time=a&return_time=a'
url+='&travelers=1&cabin=e&action=doFlights&apimode=1'
url+='&_sid_=%s&version=1' % (sid)
# XML 얻기
doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read())
# 검색 ID 추출, 검색 Url이 길어서 필요한 정보를 추출하여 리턴
searchid=doc.getElementsByTagName('searchid')[0].firstChild.data
return searchid
# 더 이상 결과가 없을 때까지 요청하는 함수
- flightsearchresults()
- parseprice()
# flight url, 결과를 제공하는 카약 함수
In [ ]:
In [ ]:
def flightsearchresults(sid,searchid):
# 앞의 $, 콤마를 없애고 숫자를 실수로 반환
def parseprice(p):
return float(p[1:].replace(',',''))
# Polling loop(확인 루프)
while 1:
time.sleep(2)
# 확인용 url 생성
url='http://www.kayak.com/s/basic/flight?'
url+='searchid=%s&c=5&apimode=1&_sid_=%s&version=1' % (searchid,sid)
doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read())
# morepending tag를 찾고 true가 아닐때까지 기다림, 완료되기 전까지는 true를 포함하고 있음
morepending=doc.getElementsByTagName('morepending')[0].firstChild
if morepending==None or morepending.data=='false': break
# 완전한 목록을 다운로드
url='http://www.kayak.com/s/basic/flight?'
url+='searchid=%s&c=999&apimode=1&_sid_=%s&version=1' % (searchid,sid)
doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read())
# 여러 요소들을 리스트로 얻음
prices=doc.getElementsByTagName('price')
departures=doc.getElementsByTagName('depart')
arrivals=doc.getElementsByTagName('arrive')
# price, depart, arrive 태그를 얻어옴
# zip(), 리스트 내의 튜플로 합치기
return zip([p.firstChild.data.split(' ')[1] for p in departures],
[p.firstChild.data.split(' ')[1] for p in arrivals],
[parseprice(p.firstChild.data) for p in prices])
# 실제 비행편검색수행이 잘 동작하는지 확인
impork kayak
sid=kayak.getkayaksession()
sid=getkayaksession()
searchid=kayak.flightsearch(sid,'BOS','LGA','11/17/2006') # 날짜는 원하는 시점으로~
f=kayak.flightsearchresults(sid,searchid)
f[0:3]
# 사람별로 처리하기
- createschedule()
# 사람별로 루프를 돌면서, 출발지와 도착지로 비행편을 검색하기
In [ ]:
In [ ]:
In [ ]:
def createschedule(people,dest,dep,ret):
# 검색용 세션 id얻기
sid=getkayaksession()
flights={}
for p in people:
name,origin=p
# 출발 비행편
searchid=flightsearch(sid,origin,dest,dep)
flights[(origin,dest)]=flightsearchresults(sid,searchid)
# 도착 비행편
searchid=flightsearch(sid,dest,origin,ret)
flights[(dest,origin)]=flightsearchresults(sid,searchid)
return flights
# 실제 비행편 데이터를 사용하여 가족비행편 최적화 (책에서는 시간문제로 2명만 적용함)
reload(kayak)
f=kayak.createschedule(optimization.people[0:2],'LGA','11/17/2006','11/19/2006'
optimizationflights=f
domain=[(0,30)]*len(f)
optimization.geneticoptimize(domain,optimization.schedulecost)
770.0
703.0
...
optimization.printschedule(s)
seymour BOS 16:00-17:20 $85.0 19:00-20:28 $65.0
Franny   DAL 08:00-17:25 $205.0 18:55-00:15 $133.0

More Related Content

What's hot

5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storage
JinKyoungHeo
 
Windows2012 active directory설치및연동
Windows2012 active directory설치및연동Windows2012 active directory설치및연동
Windows2012 active directory설치및연동
Sukjin Yun
 
MySQL과 PHP
MySQL과 PHPMySQL과 PHP
MySQL과 PHP
Yoonwhan Lee
 
Hacosa j query 4th
Hacosa j query 4thHacosa j query 4th
Hacosa j query 4th
Seong Bong Ji
 
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
Kenneth Ceyer
 
Deep dive into Modern frameworks - HTML5 Forum 2018
Deep dive into Modern frameworks - HTML5 Forum 2018Deep dive into Modern frameworks - HTML5 Forum 2018
Deep dive into Modern frameworks - HTML5 Forum 2018
Kenneth Ceyer
 
5-1. html5 graphics
5-1. html5 graphics5-1. html5 graphics
5-1. html5 graphics
JinKyoungHeo
 

What's hot (7)

5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storage
 
Windows2012 active directory설치및연동
Windows2012 active directory설치및연동Windows2012 active directory설치및연동
Windows2012 active directory설치및연동
 
MySQL과 PHP
MySQL과 PHPMySQL과 PHP
MySQL과 PHP
 
Hacosa j query 4th
Hacosa j query 4thHacosa j query 4th
Hacosa j query 4th
 
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
정적 컨텐츠 제너레이터 GatsbyJS에 대해서 알아봅시다.
 
Deep dive into Modern frameworks - HTML5 Forum 2018
Deep dive into Modern frameworks - HTML5 Forum 2018Deep dive into Modern frameworks - HTML5 Forum 2018
Deep dive into Modern frameworks - HTML5 Forum 2018
 
5-1. html5 graphics
5-1. html5 graphics5-1. html5 graphics
5-1. html5 graphics
 

Similar to 집단지성프로그래밍 05. 최적화(kayak.ipynb) 김지은_20150522

조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]
조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]
조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]
WSConf.
 
Web Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30thWeb Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30th
Chang W. Doh
 
알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations
Chang W. Doh
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
HyungKuIm
 
Web Components & Polymer
Web Components & PolymerWeb Components & Polymer
Web Components & PolymerJae Sung Park
 
Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기
Jiam Seo
 
더 나은 웹표준을 위한 Web Components
더 나은 웹표준을 위한 Web Components더 나은 웹표준을 위한 Web Components
더 나은 웹표준을 위한 Web Components정호 전
 
First Step In Ajax Korean
First Step In Ajax KoreanFirst Step In Ajax Korean
First Step In Ajax Korean
Terry Cho
 
[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기
[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기
[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기
Jeado Ko
 
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
Amazon Web Services Korea
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나
JeongHun Byeon
 
처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4
성일 한
 
Polymer따라잡기
Polymer따라잡기Polymer따라잡기
Polymer따라잡기
Han Jung Hyun
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
Jaeseung Ha
 
20141229 dklee docker
20141229 dklee docker20141229 dklee docker
20141229 dklee docker
DK Lee
 
Polymer, lego같이 만드는 웹어플리케이션
Polymer, lego같이 만드는 웹어플리케이션Polymer, lego같이 만드는 웹어플리케이션
Polymer, lego같이 만드는 웹어플리케이션
Jeado Ko
 
코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011Esun Kim
 
자바스크립트 프레임워크 살펴보기
자바스크립트 프레임워크 살펴보기자바스크립트 프레임워크 살펴보기
자바스크립트 프레임워크 살펴보기
Jeado Ko
 

Similar to 집단지성프로그래밍 05. 최적화(kayak.ipynb) 김지은_20150522 (20)

조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]
조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]
조은 - AMP PWA 101 [WSConf.Seoul.2017. Vol.2]
 
Web Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30thWeb Components - Part.I, @KIG 30th
Web Components - Part.I, @KIG 30th
 
알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations알아봅시다, Polymer: Web Components & Web Animations
알아봅시다, Polymer: Web Components & Web Animations
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
Web Components & Polymer
Web Components & PolymerWeb Components & Polymer
Web Components & Polymer
 
Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기Meteor React Tutorial 따라하기
Meteor React Tutorial 따라하기
 
더 나은 웹표준을 위한 Web Components
더 나은 웹표준을 위한 Web Components더 나은 웹표준을 위한 Web Components
더 나은 웹표준을 위한 Web Components
 
First Step In Ajax Korean
First Step In Ajax KoreanFirst Step In Ajax Korean
First Step In Ajax Korean
 
[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기
[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기
[XECon+PHPFest 2014] jQuery 개발자에서 AngularJS 개발자 되기
 
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나
 
처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4
 
Polymer따라잡기
Polymer따라잡기Polymer따라잡기
Polymer따라잡기
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
 
Html5 performance
Html5 performanceHtml5 performance
Html5 performance
 
20141229 dklee docker
20141229 dklee docker20141229 dklee docker
20141229 dklee docker
 
Polymer, lego같이 만드는 웹어플리케이션
Polymer, lego같이 만드는 웹어플리케이션Polymer, lego같이 만드는 웹어플리케이션
Polymer, lego같이 만드는 웹어플리케이션
 
테스트
테스트테스트
테스트
 
코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011
 
자바스크립트 프레임워크 살펴보기
자바스크립트 프레임워크 살펴보기자바스크립트 프레임워크 살펴보기
자바스크립트 프레임워크 살펴보기
 

More from jieun kim

KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603
KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603 KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603
KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603
jieun kim
 
OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728
OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728
OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728
jieun kim
 
150625 마이크로커널 운영체제 김지은
150625 마이크로커널 운영체제 김지은150625 마이크로커널 운영체제 김지은
150625 마이크로커널 운영체제 김지은
jieun kim
 
150326 openstack, glance 김지은
150326 openstack, glance 김지은150326 openstack, glance 김지은
150326 openstack, glance 김지은
jieun kim
 
20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은
20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은
20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은
jieun kim
 
집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522
jieun kim
 
집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522
jieun kim
 
20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은
jieun kim
 
20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은
jieun kim
 
Ryu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST APIRyu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST API
jieun kim
 
Ryu with OpenFlow 1.3, Traffic Monitor
Ryu with OpenFlow 1.3, Traffic MonitorRyu with OpenFlow 1.3, Traffic Monitor
Ryu with OpenFlow 1.3, Traffic Monitor
jieun kim
 
Build the OpenStack Cloud with Neutron Networing, IceHouse
Build the OpenStack Cloud with Neutron Networing, IceHouseBuild the OpenStack Cloud with Neutron Networing, IceHouse
Build the OpenStack Cloud with Neutron Networing, IceHouse
jieun kim
 
20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은
20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은
20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은
jieun kim
 
150416 OpenStack Networking with Neutron Jieun, Kim
150416 OpenStack Networking with Neutron Jieun, Kim150416 OpenStack Networking with Neutron Jieun, Kim
150416 OpenStack Networking with Neutron Jieun, Kim
jieun kim
 
resource on openstack
 resource on openstack resource on openstack
resource on openstack
jieun kim
 

More from jieun kim (15)

KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603
KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603 KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603
KrDAG 오픈소스를 활용하여 웹블로그 만들기_김지은_201603
 
OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728
OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728
OpenStack Korea 2015 상반기스터디(devops) 스크립트로 오픈스택 설치하기 20150728
 
150625 마이크로커널 운영체제 김지은
150625 마이크로커널 운영체제 김지은150625 마이크로커널 운영체제 김지은
150625 마이크로커널 운영체제 김지은
 
150326 openstack, glance 김지은
150326 openstack, glance 김지은150326 openstack, glance 김지은
150326 openstack, glance 김지은
 
20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은
20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은
20150525 open flow1.3_ryu_sdn_link aggregation 1_김지은
 
집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization.ipynb) 김지은_20150522
 
집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522
집단지성프로그래밍 05. 최적화(optimization) 김지은_20150522
 
20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 4 김지은
 
20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은
20150509 unix v6로 배우는 커널의 원리와 구조 3 김지은
 
Ryu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST APIRyu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST API
 
Ryu with OpenFlow 1.3, Traffic Monitor
Ryu with OpenFlow 1.3, Traffic MonitorRyu with OpenFlow 1.3, Traffic Monitor
Ryu with OpenFlow 1.3, Traffic Monitor
 
Build the OpenStack Cloud with Neutron Networing, IceHouse
Build the OpenStack Cloud with Neutron Networing, IceHouseBuild the OpenStack Cloud with Neutron Networing, IceHouse
Build the OpenStack Cloud with Neutron Networing, IceHouse
 
20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은
20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은
20150502 unix v6로 배우는 커널의 원리와 구조 1 김지은
 
150416 OpenStack Networking with Neutron Jieun, Kim
150416 OpenStack Networking with Neutron Jieun, Kim150416 OpenStack Networking with Neutron Jieun, Kim
150416 OpenStack Networking with Neutron Jieun, Kim
 
resource on openstack
 resource on openstack resource on openstack
resource on openstack
 

집단지성프로그래밍 05. 최적화(kayak.ipynb) 김지은_20150522

  • 1. In [ ]: In [ ]: # kayak http://www.kayak.com/flights/SEL-JFK/2015-05-22/2015-05-22 http://www.programmableweb.com/api/kayak # 개발자 키 다운로드 http://www.kayak.com/labs/api/search "deprecated" # minidom 패키지: XML 문서를 객체 트리로 다루는 표준 방법인 DOM인턴페이스의 경량 구현물 >>>import xml.dom.minidom >>>dom=xml.dom.minidom.parseString('<data><rec>Hello!</rec></data)') >>>dom <xml.dom.minidom.Document instance at 0x00980C28> >>>r=dom.getElementsByTagName('rec')   # getElementsByTagName('rec') >>>r [<DOM Element: rec at 0xa42350>] >>>r[0].firstChild       # firstChild, "Hello"텍스트를 가진 노드 [DOM Text node "Hello!"] >>>r[0].firstChild.data   # data, 보통 유니코드 문자열 u'Hello!' # 비행편 검색 # 개발자 키를 사용하여 새로운 카약 세션 얻기 - getkayaksession() import time import urllib2 import xml.dom.minidom kayakkey='YOUR KEY HERE' def getkayaksession(): # 세션을 시작할 URL을 생성 url='http://www.kayak.com/k/ident/apisession?token=%s&version=1' % kayakkey # 결과로 나온 XML을 파싱 doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read()) # <sid>xxxxxxxx</sid> 찾기 sid=doc.getElementsByTagName('sid')[0].firstChild.data return sid
  • 2. In [ ]: # 비행편을 검색하는 함수 - flightsearch() def flightsearch(sid,origin,destination,depart_date): # 검색 Url을 생성 url='http://www.kayak.com/s/apisearch?basicmode=true&oneway=y&origin=%s' % origin url+='&destination=%s&depart_date=%s' % (destination,depart_date) url+='&return_date=none&depart_time=a&return_time=a' url+='&travelers=1&cabin=e&action=doFlights&apimode=1' url+='&_sid_=%s&version=1' % (sid) # XML 얻기 doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read()) # 검색 ID 추출, 검색 Url이 길어서 필요한 정보를 추출하여 리턴 searchid=doc.getElementsByTagName('searchid')[0].firstChild.data return searchid # 더 이상 결과가 없을 때까지 요청하는 함수 - flightsearchresults() - parseprice() # flight url, 결과를 제공하는 카약 함수
  • 3. In [ ]: In [ ]: def flightsearchresults(sid,searchid): # 앞의 $, 콤마를 없애고 숫자를 실수로 반환 def parseprice(p): return float(p[1:].replace(',','')) # Polling loop(확인 루프) while 1: time.sleep(2) # 확인용 url 생성 url='http://www.kayak.com/s/basic/flight?' url+='searchid=%s&c=5&apimode=1&_sid_=%s&version=1' % (searchid,sid) doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read()) # morepending tag를 찾고 true가 아닐때까지 기다림, 완료되기 전까지는 true를 포함하고 있음 morepending=doc.getElementsByTagName('morepending')[0].firstChild if morepending==None or morepending.data=='false': break # 완전한 목록을 다운로드 url='http://www.kayak.com/s/basic/flight?' url+='searchid=%s&c=999&apimode=1&_sid_=%s&version=1' % (searchid,sid) doc=xml.dom.minidom.parseString(urllib2.urlopen(url).read()) # 여러 요소들을 리스트로 얻음 prices=doc.getElementsByTagName('price') departures=doc.getElementsByTagName('depart') arrivals=doc.getElementsByTagName('arrive') # price, depart, arrive 태그를 얻어옴 # zip(), 리스트 내의 튜플로 합치기 return zip([p.firstChild.data.split(' ')[1] for p in departures], [p.firstChild.data.split(' ')[1] for p in arrivals], [parseprice(p.firstChild.data) for p in prices]) # 실제 비행편검색수행이 잘 동작하는지 확인 impork kayak sid=kayak.getkayaksession() sid=getkayaksession() searchid=kayak.flightsearch(sid,'BOS','LGA','11/17/2006') # 날짜는 원하는 시점으로~ f=kayak.flightsearchresults(sid,searchid) f[0:3] # 사람별로 처리하기 - createschedule() # 사람별로 루프를 돌면서, 출발지와 도착지로 비행편을 검색하기
  • 4. In [ ]: In [ ]: In [ ]: def createschedule(people,dest,dep,ret): # 검색용 세션 id얻기 sid=getkayaksession() flights={} for p in people: name,origin=p # 출발 비행편 searchid=flightsearch(sid,origin,dest,dep) flights[(origin,dest)]=flightsearchresults(sid,searchid) # 도착 비행편 searchid=flightsearch(sid,dest,origin,ret) flights[(dest,origin)]=flightsearchresults(sid,searchid) return flights # 실제 비행편 데이터를 사용하여 가족비행편 최적화 (책에서는 시간문제로 2명만 적용함) reload(kayak) f=kayak.createschedule(optimization.people[0:2],'LGA','11/17/2006','11/19/2006' optimizationflights=f domain=[(0,30)]*len(f) optimization.geneticoptimize(domain,optimization.schedulecost) 770.0 703.0 ... optimization.printschedule(s) seymour BOS 16:00-17:20 $85.0 19:00-20:28 $65.0 Franny   DAL 08:00-17:25 $205.0 18:55-00:15 $133.0