不明白为什么这个TypeError:必须是str,而不是float异常

时间:2017-04-27 11:24:56

标签: python string web web-scraping

st1= str()
c1= str()
c2= str()
EndCash = float()

page = requests.get('http://www.xe.com/currencyconverter/convert/?Amount=' +
                    str(st1) + '&From=' + (c1) + '&To=' + (c2))
tree = html.fromstring(page.content)
rate = tree.xpath('//span[@class="uccResultAmount"]/text()')
symbol = tree.xpath('//span[@class="uccToCurrencyCode"]/text()')

EndCash = rate + symbol

我正在使用requests模块和lxml来从互联网上获取货币汇率。这样做时我遇到了问题。我收到must be str, not float错误。我在tkinter中使用这行代码作为标签,因此EndCash的输出应出现在标签中。此代码独立工作,但在tkinter中无法正常工作

>>>TypeError: must be str, not float

on first statememt。

1 个答案:

答案 0 :(得分:0)

像这样你的代码应该工作,你必须在定义它们之后将浮点数转换为字符串

page = requests.get('http://www.xe.com/currencyconverter/convert/?Amount=' + str(st1) + '&From='+str(c1) +'&To=' + str(c2))
tree = html.fromstring(page.content)
rate = tree.xpath('//span[@class="uccResultAmount"]/text()')
symbol = tree.xpath('//span[@class="uccToCurrencyCode"]/text()')

EndCash = str(rate + symbol)