值错误:无法在 Python 3 中将字符串转换为浮点数:''

您所在的位置:网站首页 python将浮点数转化为字符串的方法 值错误:无法在 Python 3 中将字符串转换为浮点数:''

值错误:无法在 Python 3 中将字符串转换为浮点数:''

2023-04-19 15:34| 来源: 网络整理| 查看: 265

我正在用Python编写一个小机器人,但我遇到了一个问题。这似乎是一个常见的问题,但我从未见过它在我所处的相同情况下被问到。

好的,所以这是代码提出问题:

old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)是一个硒工具,用于获取网站的价值。正如您稍后将看到的,检索到的元素是一个应该与 float() 一起使用的数字 “remove prc” 是我创建的用于删除数字百分比的小函数,这里是:

def removeprc(string): #removes the % from a string 

    string = str(string)

    list = string.split('%')

    string = " ".join(list)

    

    return string

这可能不是最好的方法,但当我单独测试它时,它有效。

无论如何,这是我在运行整个代码时得到的

loading page ...

page loaded

acquiring values ...

values acquired

running eth trade

-0.37

Traceback (most recent call last):

  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in

    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)

ValueError: could not convert string to float: ''

前5行是无用的。在第6行,我打印了我试图获得的浮点()的东西。如您所见,它应该工作并且...确实如此!有时。

这是最奇怪的事情,它完美地工作了一半!我在互联网上读到,如果你试图漂浮()不是数字或里面有奇怪狗屎的东西,比如空格,可能会发生这种情况。正如你所看到的,我认为这里的情况并非如此。

当我尝试通过运行简化版本的程序来隔离问题时,如下所示:

a = "-0.06%"

def removeprc(string): #removes the % from a string 

    string = str(string)

    list = string.split('%')

    string = " ".join(list)

    return string

b = float(removeprc(a))

print(b)

它输出-0.06并完美地工作???

所以我真的被困在这里。它应该有效,但它不起作用。更糟糕的是,它有时无缘无故地起作用。当我隔离问题时,它工作正常。

任何帮助将不胜感激!

哦,如果你想看到整个代码,它在这里:https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3