我一直在努力为世界制造货币转换器。我遇到的许多问题之一是我的货币转换器本身并不能算出汇率;你不得不。但当然,我明白了。
但我的问题是:我得到了欧元的汇率,但它是一个清单,我需要一个浮点来进行计算。我该怎么做?
以下是我尝试的内容:
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
######################################################################
euro_exchange = tree.xpath('//div[@class="price"]/text()')
float(str(euro_exchange)
################################################################
euro_exchange = float(tree.xpath('//div[@class="price"]/text()')
你得到了模式。当我尝试euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
时,它说(我使用TkInter,BTW):
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/jboyadvance/Documents/Code/Python/Currency Converter/Alpha2/main.py", line 21, in usd_callback
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
ValueError: could not convert string to float: "['1.1394']"
当我尝试euro_exchange = tree.xpath('//div[@class="price"]/text()')
float(str(euro_exchange)
时,我得到了相同的结果。
当我尝试euro_exchange = float(tree.xpath('//div[@class="price"]/text()')
时:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/jboyadvance/Documents/Code/Python/Currency Converter/Alpha2/main.py", line 21, in usd_callback
euro_exchange = float(tree.xpath('//div[@class="price"]/text()'))
TypeError: float() argument must be a string or a number, not 'list'
以下是源代码:
import tkinter as tk
from lxml import html
import requests
window = tk.Tk()
window.title("Currency Converter")
window.geometry("500x500")
window.configure(bg="#900C3F")
# window.wm_iconbitmap("penny.ico")
page = requests.get('https://www.bloomberg.com/quote/EURUSD:CUR')
tree = html.fromstring(page.content)
def usd_callback():
usd_amount = float(ent_usd.get())
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
euro_amount = usd_amount / euro_exchange
lbl_euros.config(text="Euro Amount: %.2f€" % euro_amount)
lbl_usd = tk.Label(window, text="Enter the USD ($) here:", bg="#900C3F", font="#FFFFFF")
ent_usd = tk.Entry(window)
btn_usd = tk.Button(window, text="Convert", command=usd_callback, bg="#FFFFFF", font="#FFFFFF")
lbl_euros = tk.Label(window)
lbl_usd.pack()
ent_usd.pack()
btn_usd.pack()
window.mainloop()
欢迎任何帮助!谢谢!!
答案 0 :(得分:2)
您需要转换xpath
的返回值中的第一个元素:
euro_exchange = tree.xpath('//div[@class="price"]/text()')
euro_exchange = float(str(euro_exchange[0]))