Skip to content

Instantly share code, notes, and snippets.

@ltiao
Last active December 13, 2015 19:18
Show Gist options
  • Save ltiao/4961149 to your computer and use it in GitHub Desktop.
Save ltiao/4961149 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import requests, optparse
from bs4 import BeautifulSoup
PRECISION = 2
VERBOSE = False
parser = optparse.OptionParser()
parser.add_option('-f', '--from', action="store", dest="from")
parser.add_option('-t', '--to', action="store", dest="to")
parser.add_option('-a', '--amount', action="store", dest="amount", type="float")
options, args = parser.parse_args()
base_url = 'http://www.x-rates.com/calculator/'
r = requests.get(base_url, params=vars(options))
soup = BeautifulSoup(r.text)
result = list(soup.find("span", {"class": "ccOutputRslt"}).stripped_strings)
result_dict = {
'currency': result[-1],
'amount': float(''.join(result[:-1]).replace(",", "")),
'meta': {
'currency_from_to_string': soup.find("span", {"class": "OutputArgs"}).string,
'from_amount_string': soup.find("span", {"class": "ccOutputTxt"}).string,
'timestamp': soup.find("span", {"class": "calOutputTS"}).string
}
}
if VERBOSE:
print 'Result accurate as of: {time}'.format(time=result_dict['meta']['timestamp'])
print result_dict['meta']['currency_from_to_string']
print result_dict['meta']['from_amount_string'],
print '{amount:.{precision}f} {currency}'.format(amount=round(result_dict['amount'], PRECISION), currency=result_dict['currency'], precision=PRECISION)
@ltiao
Copy link
Author

ltiao commented Feb 15, 2013

LOL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment