[英]Python Selenium Webelement to Float
我遇到以下问题:我正在尝试将我的网络元素转换为浮动。
asd = driver.find_element_by_xpath("/html/body/div[2]/div[4]/div[2]/div[2]/div[2]/div/div/div/table/tbody/tr[3]/td[17]")
print (float(asd.text.strip()))
收到此错误:
print (float(asd.text.strip()))
ValueError: could not convert string to float: '3,56'
谢谢!
该字符串不是 python 可识别的浮点格式。 您可以将其更改为句点(使用float(asd.text.strip().replace(",", "."))
或使用语言环境:
from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, "YOURLOCALE") # a locale where commas are used as the decimal point
atof(asd.text.strip())
无论您使用哪种方法,您都必须确保语法在您运行代码的所有站点/页面上保持一致。
试试这个:
print (float(asd.text.strip().replace(",",".")))
文本返回元素的可见文本。
在您的用例中,返回的文本包含3,56中的逗号,因此float()
将无法将返回的文本(包含逗号)自动转换为浮点类型。 因此您会看到错误:
ValueError: could not convert string to float: '3,56'
您需要.
点ie 替换逗号ie ,
然后调用float()
,您可以使用以下解决方案:
使用replace()
的代码块:
asd = driver.find_element_by_xpath("/html/body/div[2]/div[4]/div[2]/div[2]/div[2]/div/div/div/table/tbody/tr[3]/td[17]") # asd = "3,56" print(float(asd.replace(",","."))) print(type(float(asd.replace(",","."))))
控制台 Output:
3.56 <class 'float'>
如果您想完全删除逗号字符 ie ,
并将结果文本 ie 356转换为浮点数,您可以使用以下解决方案:
使用re()
的代码块:
import re asd = driver.find_element_by_xpath("/html/body/div[2]/div[4]/div[2]/div[2]/div[2]/div/div/div/table/tbody/tr[3]/td[17]") # asd = "3,56" print(float(re.sub('[,]', '', asd))) print(type(float(re.sub('[,]', '', asd))))
控制台 Output:
356.0 <class 'float'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.