ESTRUTURA DE PASTAS DO PROJETO:
- Arquivo Principal: string_extraindo_info_url/src/main.py
- Arquivo de excessões: string_extraindo_info_url/exceptions/exceptions.py
ARQUIVO main.py
from exceptions.exceptions import *
class ExtratorURL
def __init__(self, url):
self.url = url
self.url_validation()
self.dict_variables_values = {}
def get_url_base(self):
base_url = url.split('?')[0]
return base_url
def get_value_variable(self, variable):
self.extract_variables()
if self.variable_is_empty(variable):
raise VariableIsEmpty('O campo da variável está vazia.')
elif self.variable_is_in_url(variable):
return self.dict_variables_values[variable]
else:
raise VariableDoesNotExists(f'O parâmetro ou variável "{variable}" não existe nessa url')
def extract_variables(self):
raw_variables = url.split('?')[-1]
variables_with_value_list = raw_variables.split('&')
variables_list = tuple(map(lambda x: x.split('=')[0], variables_with_value_list))
values_list = tuple(map(lambda x: x.split('=')[1], variables_with_value_list))
for i, j in enumerate(variables_list):
key = variables_list[i]
value = values_list[i]
self.dict_variables_values[key] = value
def url_validation(self):
if not self.url:
raise UrlIsEmpty('Url está vazia')
else:
self.sanitization_url()
def sanitization_url(self):
self.url = self.url.strip()
def variable_is_in_url(self, variable):
return variable in self.dict_variables_values.keys()
def variable_is_empty(self, variable):
return len(variable.strip()) == 0
if __name__ == '__main__':
url = 'https://bytebank.com/cambio?moedaOrigem=real&moedaDestino=dolar&quantidade=100'
empty_url = ''
extractor = ExtratorURL(url)
base_url = extractor.get_url_base()
print(extractor.get_value_variable('quantidade'))
print(base_url)
ARQUIVO exceptions.py
class UrlIsEmpty(Exception):
pass
class VariableDoesNotExists(Exception):
pass
class VariableIsEmpty(Exception):
pass