汇率转换小程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import requests
from lxml import etree

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
}
url = "https://www.huilv.cc/USD_CNY/"

def Get_huilv(url, headers1, currency_str_value):
res = requests.get(url=url, headers=headers1, timeout=2)
# print(res.status_code) # 打印状态码
html = etree.HTML(res.text)
USD_VS_RMB_0 = html.xpath('//div[@id="main"]/div[1]/div[2]/span[1]/text()')
for a in USD_VS_RMB_0:
b = a
USD_VS_RMB_1 = float(b)
print("实时汇率为:{}".format(USD_VS_RMB_1))
USD_VS_RMB = float(str(USD_VS_RMB_1))

# 获取货币单位
unit = currency_str_value[-3:].upper() # 第一次判断
if unit == 'CNY':
exchange_rate = 1 / USD_VS_RMB
string = "美元"
elif unit == 'USD':
exchange_rate = USD_VS_RMB
string = "元"
else:
exchange_rate = -1
if exchange_rate != -1:
in_money = eval(currency_str_value[0:-3])
# 使用lambda定义函数
convert_currency2 = lambda x: x * exchange_rate
# 调用lambda函数
out_money = convert_currency2(in_money)
print('转换后的金额是:{} {} '.format(out_money, string))
else:
print('无法计算')

Get_huilv(url, headers, '100 CNY')