ValueError: could not convert string to float: '' in python 3

♀尐吖头ヾ 提交于 2021-02-11 09:38:02

问题


So I'm coding a little bot in python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem :

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) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number wich should work with float() "remove prc" is a little function I created to remove the % of a number, here it is :

def removeprc(string): #removes the % from a string 
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

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 <module>
    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: ''

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float() of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time! I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, i think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

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)

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py


回答1:


This error message...

ValueError: could not convert string to float: ''

...implies that the Python interpreter was unable to convert a string to float.


You were close enough. text method would return a string and to strip off the %, instead of string.split('%') you want list = string.split('%')[0].

An example:

my_percentage = "99%"
my_string_num = my_percentage.split("%")[0]
print(my_string_num)

prints:

99

Further, find_element_by_xpath() will identify only a single element, and using text you would get a single string, so string = " ".join(list) seems redundant.

So effectively, to strip the %, convert the string to float and print, your effective line of code will be:

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

Update

You are still seeing the error as the element with the required text haven't rendered within the DOM when the line of code is invoked. As a solution you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following Locator Strategy:

print(float(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='draggableNavRightResizable']/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span"))).text.split("%")[0]))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC



回答2:


You have used the keyword as a variable here. That's why sometimes it doesn't work I guess. Like str(), list() is a method to convert a variable into a list. Try to rename the variable like below, I guess.

def removeprc(string): #removes the % from a string 
    string = str(string)
    l = string.split('%')
    string = " ".join(l)
    return string



回答3:


The returned text is an empty string, so it can't be converted to float. Add a check

b = removeprc(a)
if b:
    print(float(b))
else:
    print('b is an empty string')


来源:https://stackoverflow.com/questions/60291334/valueerror-could-not-convert-string-to-float-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!