ARQUIVO PRINCIPAL: string_extraindo_info_url/src/main.py
import re
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()
url_pattern = re.compile('(http(s)?://)?(www.)?bytebank.com(.br)?/cambio')
match = url_pattern.match(url)
if not match:
raise InvalidURL('A URL é inválida')
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
@property
def parameters(self):
self.extract_variables()
return self.dict_variables_values.keys()
@property
def values(self):
self.extract_variables()
return self.dict_variables_values.values()
def __len__(self):
return len(self.url)
def __str__(self):
return f'URL: {self.url}\n' \
f'Variables: {self.parameters}\n' \
f'Values: {self.values}\n' \
f'URL Base: {self.get_url_base()}'
def __eq__(self, other_extractor):
return self.url == other_extractor.url
if __name__ == '__main__':
url = 'https://bytebank.com/cambio?moedaOrigem=real&moedaDestino=dolar&quantidade=100'
empty_url = ''
extractor = ExtratorURL(url)
extractor2 = ExtratorURL(url)
print(extractor)
print(f'Tamanho: {len(extractor)}')
print(f'Valor do parâmetro "quantidade": {extractor.get_value_variable("quantidade")}')
print(f'Is the extractor equal to extractor2 ? {extractor==extractor2}')
ARQUIVO DE EXCESSOES: string_extraindo_info_url/exceptions/exceptions.py
class URLIsEmpty(Exception):
pass
class VariableDoesNotExists(Exception):
pass
class VariableIsEmpty(Exception):
pass
class InvalidURL(Exception):
pass