Skip to content

Instantly share code, notes, and snippets.

@axiak
Created December 17, 2011 00:01
Show Gist options
  • Save axiak/1488604 to your computer and use it in GitHub Desktop.
Save axiak/1488604 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import csv
import sys
import urllib
import BeautifulSoup
def main():
reader = csv.reader(sys.stdin)
writer = csv.writer(sys.stdout)
writer.writerow(reader.next())
for row in reader:
if len(row) < 9:
row += [''] * (9 - len(row))
if row[7].strip() and row[8].strip():
writer.writerow(row)
continue
#print list(enumerate(row))
distance, time = get_time_and_distance(row[5], row[6])
row[7] = distance
row[8] = time
writer.writerow(row)
def get_time_and_distance(saddr, daddr):
url = 'http://maps.google.com/m/directions?ie=UTF8&hl=en&f=d&dirflg=&' + \
urllib.urlencode({'saddr': saddr, 'daddr': daddr})
response = urllib.urlopen(url).read()
root = BeautifulSoup.BeautifulSoup(response)
try:
time = root.find('b').text.strip()
except:
time = '#NA'
try:
distance = str(root.findAll('p')[2]).split('- about')[0].split('<br />')[1].strip()
except:
distance = '#NA'
return distance, time
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment