简体   繁体   中英

Regex bank account balance using selenium in python

I am working on a Python3 program that uses Selenium to open a web browser in Chrome then navigates to the Bank of America account information page. However, I am having trouble with extracting the actual account balance from a string that contains a dollar sign.

I want to extract the value from the account balance and store the number without the dollar sign. How would I do this?

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

This line balanceValue = balanceValue.text sets balanceValue to an instance of a str , you can verify this by running type(balanceValue) .

To get a substring at the first index to the end (which would exclude the '$' character), you can do:

balanceSubstr = balanceValue[1:]

Aside: in order to keep the usage of variables clear, I would recommend the following refactoring:

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

CamelCase is generally reserved for class named in Python while instances are denoted with_underscores_like_this.

If you really want to use the regular expression to extract the value, you can use the below.

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

This will make sure even if your output have space between the dollar symbol and value like $ 123.45 . In this case the [1:] approach will give you the incorrect information. And you can use this regular expression against any currency eg: Rs.123.45

在此处输入图片说明

If you want to simplify it you can do

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

在此处输入图片说明

you can use lstrip to strip a character from the left side of a string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM