בדיקת שערי מט"ח באמצעות פייתון
פורסמה על־ידי ozzyboy ב- 09/12/2010
סקריפט קצר בפייתון שמשתמש בספריה הסטנדרטית של פייתון בשביל להביא את נתוני המט"ח העדכניים
מהאתר של בנק ישראל (אשר זמינים בפורמט XML), ומפענח את אותו XML באמצעות ספריית ה minidom אשר מגיעה גם היא כחלק מהספריה הסטנדרטית של פייתון.
הסקריפט רחוק מלהיות מושלם ובוחר שלא להתמודד כלל עם שגיאות אפשריות – אבל הוא עושה את העבודה ומשמש בעיקר לשם ההדגמה.
אם מישהו ימצא את זה שימושי, מה טוב.
#!/usr/bin/env python
import urllib2
from xml.dom import minidom as dom
def get_tag_str_content(xml_tag):
for c in xml_tag.childNodes:
if c.nodeType == c.TEXT_NODE:
return c.nodeValue # Return the first text node found.
return None
def get_rate_by_code(currency_code):
# Fetch and parse the XML from the bank of israel
response = urllib2.urlopen('http://www.bankisrael.gov.il/currency.xml')
xml_doc = dom.parseString(response.read())
# Search for the required currency
for currency in xml_doc.getElementsByTagName('CURRENCY'):
curr_elem = currency.getElementsByTagName('CURRENCYCODE')[0]
curr = get_tag_str_content(curr_elem)
if curr == currency_code:
# Get the current rate, and convert it into a float
rate_elem = currency.getElementsByTagName('RATE')[0]
return float(get_tag_str_content(rate_elem))
return None # If the currency code is not found
if __name__ == '__main__':
rate = get_rate_by_code('USD')
print('the current rate of the US dollar is: %.3f nis' % (rate))
שבת שלום.
אייל כתב/ה
אני בדיוק צריך כזו אפשרות בשביל עסק שמזמין מחו"ל, תודה
ozzyboy כתב/ה
מגניב, שמחתי לעזור
shahar כתב/ה
תודה על הקוד:
שיפרתי קצת, שיהיה לי שימושי.
#!/usr/bin/env pythonusage = '''israel bank foreign exchange getter
usage:
matach.py
matach.py
matach.py --help
e.g.
matach.py USD
Initiated by: oz, http://ozzyboy.wordpress.com/about/
Patched to be useful: shahar
Thanks to bank of israel for sharing information that was paid from my taxes anyway.
No thanks for spending my money for excessive weiges far beyond proportion.
'''
import sys
import urllib2
from xml.dom import minidom as dom
class Currency:
def __init__(self):
# Fetch and parse the XML from the bank of israel
response = urllib2.urlopen('http://www.bankisrael.gov.il/currency.xml')
xml_doc = dom.parseString(response.read())
self.currency_elems = xml_doc.getElementsByTagName('CURRENCY')
def get_tag_str_content(self, xml_tag):
for c in xml_tag.childNodes:
if c.nodeType == c.TEXT_NODE:
return c.nodeValue # Return the first text node found.
return None
def get_codes(self):
currencies = []
for currency in self.currency_elems:
curr_elem = currency.getElementsByTagName('CURRENCYCODE')[0]
curr = self.get_tag_str_content(curr_elem)
currencies.append(curr)
#currencies.sort() # i think it's already popularity-based ordered
return currencies
def get_rate_by_code(self, currency_code):
# Fetch and parse the XML from the bank of israel
response = urllib2.urlopen('http://www.bankisrael.gov.il/currency.xml')
xml_doc = dom.parseString(response.read())
# Search for the required currency
for currency in self.currency_elems:
curr_elem = currency.getElementsByTagName('CURRENCYCODE')[0]
curr = self.get_tag_str_content(curr_elem)
if curr == currency_code:
# Get the current rate, and convert it into a float
rate_elem = currency.getElementsByTagName('RATE')[0]
return float(self.get_tag_str_content(rate_elem))
return None # If the currency code is not found
def end(msg='press enter...'):
raw_input(msg)
sys.exit(0)
if __name__ == '__main__':
c = Currency()
print 'yes'
if len(sys.argv)<=1:
rate = c.get_rate_by_code('USD')
print('the current rate of the US dollar is: %.3f nis' % (rate))
else:
arg=sys.argv[1].upper()
currencies = c.get_codes()
if arg in ['HELP', '--HELP', '-H', '?', '/?']:
print usage
print 'currency codes:'
print ', '.join(currencies)
elif arg in currencies:
rate = c.get_rate_by_code(arg)
print('the current rate of %s: %.3f nis' % (arg, rate))
else:
print 'invalid currency code:', arg
end()
shahar כתב/ה
אוי, יש לך באג קטן. במקרה של יין, למשל, צריך לחלק בUNIT
unit_elem = currency.getElementsByTagName('UNIT')[0] rate = float( rate_elem ) / float( unit_elem ) בערך (צריך להמיר לסטרינג)