[英]Python Selenium Webelement to Float
I'm having the following issue: I'm trying to convert my 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()))
Getting this error:收到此错误:
print (float(asd.text.strip()))
ValueError: could not convert string to float: '3,56'
Thank you!谢谢!
The string is not in the float format that python recognizes.该字符串不是 python 可识别的浮点格式。 You can either change it to a period (using float(asd.text.strip().replace(",", "."))
or using locale:您可以将其更改为句点(使用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())
Either method you use, you have to make sure the syntax is consistent over all the sites/pages you run your code on.无论您使用哪种方法,您都必须确保语法在您运行代码的所有站点/页面上保持一致。
try this:试试这个:
print (float(asd.text.strip().replace(",",".")))
text returns the visible text of the element. 文本返回元素的可见文本。
In your usecase, the returned text contains a comma as in 3,56 , hence float()
won't be able to convert the returned text (which contains a comma) automatically into a float type.在您的用例中,返回的文本包含3,56中的逗号,因此float()
将无法将返回的文本(包含逗号)自动转换为浮点类型。 Hence you see the error:因此您会看到错误:
ValueError: could not convert string to float: '3,56'
You need to replace the comma ie ,
with a dot ie .
您需要.
点ie 替换逗号ie ,
and then invoke float()
and you can use the following solution:然后调用float()
,您可以使用以下解决方案:
Code Block using replace()
:使用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(",","."))))
Console Output:控制台 Output:
3.56 <class 'float'>
Incase, you want to completely remove the comma character ie ,
and convert the resultant text ie 356 into float you can use the following solution:如果您想完全删除逗号字符 ie ,
并将结果文本 ie 356转换为浮点数,您可以使用以下解决方案:
Code Block using re()
:使用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))))
Console Output:控制台 Output:
356.0 <class 'float'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.