3 回答

TA贡献1827条经验 获得超9个赞
此错误消息...
ValueError: could not convert string to float: ''
...这意味着Python解释器无法将字符串转换为浮点数。
你离得足够近了。text 方法将返回一个字符串并去掉 ,而不是您想要的 。%string.split('%')list = string.split('%')[0]
例如:
my_percentage = "99%"
my_string_num = my_percentage.split("%")[0]
print(my_string_num)
指纹:
99
此外,将仅标识单个元素,并使用文本您将获得单个字符串,因此似乎是多余的。find_element_by_xpath()string = " ".join(list)
因此,有效地,要剥离 ,将字符串转换为浮点型和打印型,您的有效代码行将是:%
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]))
更新
您仍然看到错误,因为调用代码行时,具有所需文本的元素尚未在 DOM 中呈现。作为解决方案,您需要诱导WebDriverWait,并且可以使用以下定位器策略:visibility_of_element_located()
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]))
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

TA贡献1799条经验 获得超8个赞
返回的文本为空字符串,因此无法转换为 。添加支票float
b = removeprc(a)
if b:
print(float(b))
else:
print('b is an empty string')

TA贡献1839条经验 获得超15个赞
您在此处使用了关键字作为变量。这就是为什么有时它不起作用。与 str() 一样,list() 是一种将变量转换为列表的方法。我想,尝试重命名变量,如下所示。
def removeprc(string): #removes the % from a string
string = str(string)
l = string.split('%')
string = " ".join(l)
return string
添加回答
举报