ValueError: could not convert string to float: '' in Python 3
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 WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC
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
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')