在python中使用硒的正则表达式银行帐户余额

时间:2019-09-05 01:52:08

标签: python regex selenium

我正在研究一个Python3程序,该程序使用Selenium在Chrome中打开网络浏览器,然后导航到美国银行帐户信息页面。但是,我在从包含美元符号的字符串中提取实际帐户余额时遇到了麻烦。

我想从帐户余额中提取值并存储不带美元符号的数字。我该怎么办?

from selenium import webdriver
... # Logins in & navigates to account info
balanceValue = browser.find_element_by_class_name('AccountBalance')
balanceValue = balanceValue.text


print(balanceValue)
$415.24

# I want the following output without the dollar sign
print(balanceValue)
415.24

3 个答案:

答案 0 :(得分:0)

此行balanceValue = balanceValue.text将balanceValue设置为str的实例,您可以通过运行type(balanceValue)进行验证。

要在第一个索引末尾获得一个子字符串(这将排除'$'字符),可以执行以下操作:

balanceSubstr = balanceValue[1:]

此外:为了保持变量的用法清晰,我建议进行以下重构:

balance_element = browser.find_element_by_class_name('AccountBalance')
balance_text = balance_value.text[1:]
balance = float(balance_text)

通常将CamelCase保留给Python命名的类,而将实例表示为with_underscores_like_this。

答案 1 :(得分:0)

如果您确实要使用正则表达式提取值,则可以使用以下内容。

import re
match = re.search("\d+\.\d*","$123.45")
value = match.group(0)

这将确保即使输出的美元符号和值之间有空格,如$ 123.45。在这种情况下,[1:]方法将为您提供错误的信息。您可以针对任何货币使用此正则表达式,例如:Rs.123.45

enter image description here

如果要简化它,可以做

value = re.search("\d+\.\d*","$123.45")[0]

enter image description here

答案 2 :(得分:0)

您可以使用lstrip从字符串的左侧剥离字符:

>>> balance = '$415.24'
>>> balance_value = balance.lstrip('$')
>>> print(balance_value)
415.24