如何在python中转换货币?

时间:2017-09-15 08:16:08

标签: python list currency

我正在开发一个虚拟助手项目。我希望它以其他货币告诉我美元汇率。 我使用beautifulsoup编写了以下代码,它从给定的网站获取数据,解析它并在命令行中打印结果供我阅读。但这只是美元对PKR的影响。如何修改程序以便使用任何货币并告诉我该货币的转换率? 例如,如果我问它“英国的美元汇率是多少?”,“阿联酋的英镑汇率是多少”,“美国的欧元汇率是多少?”它返回转换率。我所指的代码如下。

import urllib.request
from bs4 import BeautifulSoup

currency_page = 'http://www.xe.com/currencyconverter/convert/?Amount=1&From=USD&To=PKR'
currency = urllib.request.urlopen(currency_page)
currency_data = BeautifulSoup(currency, 'html.parser')

USD = currency_data.find('span', attrs={'class': 'uccResultUnit'})
USD_PKR = USD.text.strip() # strip() is used to remove starting and trailing
print(USD_PKR)

我尝试修改网址http://www.xe.com/currencyconverter/convert/?Amount=1&From=USD&To=PKR 并替换 Amount=1, From=USD, To=PKR

使用 Amount= custom_amount, From= any_source_curreny, To=any_target_currency 并将多个货币名称传递给变量,但我对此感到困惑。任何人都可以建议如何做到这一点?任何帮助表示赞赏。感谢

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案是根据用户输入动态构建您的网址(您可以使用str.format()来执行此操作)。例如:

#!/usr/bin/env python

from requests import get
from bs4 import BeautifulSoup
import sys

v1 = sys.argv[1]
v2 = sys.argv[2]
amount = sys.argv[3]

# check if the values passed are valid
# and construct the url like so:
currency_page = 'http://www......../convert/?Amount={}&From={}&To={}'.format(amount,v1,v2)

currency = get(currency_page).text
currency_data = BeautifulSoup(currency, 'html.parser')

USD = currency_data.find('span', attrs={'class': 'uccResultUnit'})
USD_PKR = USD.text.strip()
print(USD_PKR)

结果:

$ ./test.py EUR PKR 1                           
1 EUR = 125.790 PKR

另一个解决方案,也在评论中提到,是使用

  1. API或
  2. 一个模块。