csc-cia-stne 0.1.0__py3-none-any.whl → 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- csc_cia_stne/utilitarios/functions/func_get_secret.py +5 -5
- csc_cia_stne/utilitarios/web_screen/__init__.py +2 -0
- csc_cia_stne/utilitarios/web_screen/web_screen_abstract.py +84 -0
- csc_cia_stne/utilitarios/web_screen/web_screen_botcity.py +285 -0
- csc_cia_stne/utilitarios/web_screen/web_screen_selenium.py +350 -0
- csc_cia_stne/web.py +44 -486
- {csc_cia_stne-0.1.0.dist-info → csc_cia_stne-0.1.2.dist-info}/METADATA +1 -1
- {csc_cia_stne-0.1.0.dist-info → csc_cia_stne-0.1.2.dist-info}/RECORD +11 -7
- {csc_cia_stne-0.1.0.dist-info → csc_cia_stne-0.1.2.dist-info}/WHEEL +0 -0
- {csc_cia_stne-0.1.0.dist-info → csc_cia_stne-0.1.2.dist-info}/licenses/LICENCE +0 -0
- {csc_cia_stne-0.1.0.dist-info → csc_cia_stne-0.1.2.dist-info}/top_level.txt +0 -0
@@ -32,35 +32,35 @@ def get_secret(name: str, maestro: Optional[BotMaestroSDK] = None, activity_labe
|
|
32
32
|
# verifica na pasta ./secrets
|
33
33
|
if os.path.exists(f"./secrets/{name}"):
|
34
34
|
|
35
|
-
with open(f"./secrets/{name}",'r') as secret_file:
|
35
|
+
with open(f"./secrets/{name}",'r', encoding="utf-8") as secret_file:
|
36
36
|
|
37
37
|
secret = secret_file.read()
|
38
38
|
|
39
39
|
# verifica na pasta ./.secrets
|
40
40
|
elif os.path.exists(f"./.secrets/{name}"):
|
41
41
|
|
42
|
-
with open(f"./.secrets/{name}",'r') as secret_file:
|
42
|
+
with open(f"./.secrets/{name}",'r', encoding="utf-8") as secret_file:
|
43
43
|
|
44
44
|
secret = secret_file.read()
|
45
45
|
|
46
46
|
# verifica na pasta ./private
|
47
47
|
elif os.path.exists(f"./private/{name}"):
|
48
48
|
|
49
|
-
with open(f"./private/{name}",'r') as secret_file:
|
49
|
+
with open(f"./private/{name}",'r', encoding="utf-8") as secret_file:
|
50
50
|
|
51
51
|
secret = secret_file.read()
|
52
52
|
|
53
53
|
# verifica na pasta ./.private
|
54
54
|
elif os.path.exists(f"./.private/{name}"):
|
55
55
|
|
56
|
-
with open(f"./.private/{name}",'r') as secret_file:
|
56
|
+
with open(f"./.private/{name}",'r', encoding="utf-8") as secret_file:
|
57
57
|
|
58
58
|
secret = secret_file.read()
|
59
59
|
|
60
60
|
# verifica na pasta /secrets
|
61
61
|
elif os.path.exists(f"/secrets/{name}"):
|
62
62
|
|
63
|
-
with open(f"/secrets/{name}",'r') as secret_file:
|
63
|
+
with open(f"/secrets/{name}",'r', encoding="utf-8") as secret_file:
|
64
64
|
|
65
65
|
secret = secret_file.read()
|
66
66
|
|
@@ -0,0 +1,84 @@
|
|
1
|
+
from abc import ABC, abstractmethod
|
2
|
+
|
3
|
+
|
4
|
+
class WebScreenAbstract(ABC):
|
5
|
+
"""
|
6
|
+
Classe abstrata que define a interface para interações com a tela web.
|
7
|
+
Métodos Abstratos:
|
8
|
+
configuracao_inicial():
|
9
|
+
Configura o ambiente inicial para interações com a tela web.
|
10
|
+
click_on_screen(target: str, timeout: int = 10):
|
11
|
+
Clica em um elemento na tela web.
|
12
|
+
input_value(target: str, value: str, clear: bool = True):
|
13
|
+
Insere um valor em um campo de entrada na tela web.
|
14
|
+
select_value(target: str, value: str):
|
15
|
+
Seleciona um valor em um campo de seleção na tela web.
|
16
|
+
"""
|
17
|
+
|
18
|
+
@abstractmethod
|
19
|
+
def select_one_element(
|
20
|
+
self,
|
21
|
+
target: str,
|
22
|
+
time: int = 15,
|
23
|
+
webdrive_type: str = "visibilidade_do_elemento",
|
24
|
+
):
|
25
|
+
"""
|
26
|
+
Seleciona um único elemento na página da web com base no alvo especificado.
|
27
|
+
|
28
|
+
Args:
|
29
|
+
target (str): O seletor ou identificador do elemento a ser selecionado.
|
30
|
+
time (int, opcional): O tempo máximo (em segundos) para aguardar o elemento estar disponível.
|
31
|
+
O padrão é 15 segundos.
|
32
|
+
webdrive_type (str, opcional): O tipo de condição de espera para o elemento.
|
33
|
+
Pode ser, por exemplo, "visibilidade_do_elemento". O padrão é "visibilidade_do_elemento".
|
34
|
+
|
35
|
+
Raises:
|
36
|
+
NotImplementedError: Indica que o método ainda não foi implementado.
|
37
|
+
"""
|
38
|
+
raise NotImplementedError("Método 'select_element' ainda não implementado.")
|
39
|
+
|
40
|
+
@abstractmethod
|
41
|
+
def select_elements(
|
42
|
+
self,
|
43
|
+
target: str,
|
44
|
+
time: int = 15,
|
45
|
+
):
|
46
|
+
"""
|
47
|
+
Seleciona elementos na tela com base no alvo especificado.
|
48
|
+
|
49
|
+
Args:
|
50
|
+
target (str): O identificador do elemento ou grupo de elementos a serem selecionados.
|
51
|
+
time (int, opcional): O tempo máximo, em segundos, para aguardar a seleção dos elementos.
|
52
|
+
O padrão é 15 segundos.
|
53
|
+
|
54
|
+
Raises:
|
55
|
+
NotImplementedError: Exceção levantada indicando que o método ainda não foi implementado.
|
56
|
+
"""
|
57
|
+
raise NotImplementedError("Método 'select_elements' ainda não implementado.")
|
58
|
+
|
59
|
+
@abstractmethod
|
60
|
+
def close_tab(self):
|
61
|
+
"""
|
62
|
+
Fecha a aba atual do navegador.
|
63
|
+
Este método deve ser implementado para fechar a aba ativa do navegador.
|
64
|
+
"""
|
65
|
+
raise NotImplementedError("Método 'close_tab' ainda não implementado.")
|
66
|
+
|
67
|
+
@abstractmethod
|
68
|
+
def get_driver(self):
|
69
|
+
"""
|
70
|
+
Retorna o driver da instância atual.
|
71
|
+
Este método deve ser implementado para retornar a instância do driver web utilizado.
|
72
|
+
"""
|
73
|
+
raise NotImplementedError("Método 'get_driver' ainda não implementado.")
|
74
|
+
|
75
|
+
@abstractmethod
|
76
|
+
def change_tab(self, tab_index: int):
|
77
|
+
"""
|
78
|
+
Altera para a aba especificada pelo índice.
|
79
|
+
Args:
|
80
|
+
tab_index (int): Índice da aba para a qual mudar (0 para a primeira aba).
|
81
|
+
Raises:
|
82
|
+
NotImplementedError: Indica que o método ainda não foi implementado.
|
83
|
+
"""
|
84
|
+
raise NotImplementedError("Método 'change_tab' ainda não implementado.")
|
@@ -0,0 +1,285 @@
|
|
1
|
+
from selenium.webdriver.common.by import By
|
2
|
+
from webdriver_manager.chrome import ChromeDriverManager
|
3
|
+
from selenium.common.exceptions import (
|
4
|
+
TimeoutException,
|
5
|
+
WebDriverException,
|
6
|
+
NoSuchElementException,
|
7
|
+
)
|
8
|
+
|
9
|
+
# Botcity
|
10
|
+
from botcity.web import WebBot, Browser
|
11
|
+
from botcity.web.util import element_as_select
|
12
|
+
from .web_screen_abstract import WebScreenAbstract
|
13
|
+
|
14
|
+
|
15
|
+
class WebScreenBotCity(WebScreenAbstract):
|
16
|
+
"""
|
17
|
+
Classe que implementa a interface WebScreenAbstract usando BotCity.
|
18
|
+
Métodos:
|
19
|
+
configuracao_inicial():
|
20
|
+
Configura o ambiente inicial para interações com a tela web usando BotCity.
|
21
|
+
click_on_screen(target: str, timeout: int = 10):
|
22
|
+
Clica em um elemento na tela web usando BotCity.
|
23
|
+
input_value(target: str, value: str, clear: bool = True):
|
24
|
+
Insere um valor em um campo de entrada na tela web usando BotCity.
|
25
|
+
select_value(target: str, value: str):
|
26
|
+
Seleciona um valor em um campo de seleção na tela web usando BotCity.
|
27
|
+
"""
|
28
|
+
|
29
|
+
def __init__(
|
30
|
+
self,
|
31
|
+
headless: bool = True,
|
32
|
+
disable_gpu: bool = True,
|
33
|
+
no_sandbox: bool = True,
|
34
|
+
timeout: int = 10,
|
35
|
+
security: bool = False,
|
36
|
+
):
|
37
|
+
"""
|
38
|
+
Inicializa a classe com as configurações para o WebBot.
|
39
|
+
Args:
|
40
|
+
headless (bool): Define se o navegador será executado em modo headless (sem interface gráfica).
|
41
|
+
Padrão é True.
|
42
|
+
disable_gpu (bool): Define se o uso de GPU será desativado no navegador. Padrão é True.
|
43
|
+
no_sandbox (bool): Define se o navegador será executado sem o modo sandbox. Padrão é True.
|
44
|
+
timeout (int): Tempo limite (em segundos) para operações realizadas pelo WebBot. Padrão é 10.
|
45
|
+
security (bool): Define se configurações de segurança adicionais serão aplicadas. Padrão é False.
|
46
|
+
Raises:
|
47
|
+
ValueError: Caso ocorra algum erro durante a inicialização da classe.
|
48
|
+
"""
|
49
|
+
self.web_bot = None
|
50
|
+
self.timeout = timeout
|
51
|
+
self.security = security
|
52
|
+
self.screenshot = []
|
53
|
+
try:
|
54
|
+
|
55
|
+
# Criação do drive para botcity
|
56
|
+
|
57
|
+
self.web_bot = WebBot()
|
58
|
+
|
59
|
+
# Configurar o navegador (por exemplo, Chrome)
|
60
|
+
self.web_bot.browser = Browser.CHROME
|
61
|
+
|
62
|
+
self.web_bot.driver_path = ChromeDriverManager().install()
|
63
|
+
|
64
|
+
# Configurar as opções do Chrome
|
65
|
+
self.web_bot.headless = headless
|
66
|
+
self.web_bot.disable_gpu = disable_gpu
|
67
|
+
self.web_bot.no_sandbox = no_sandbox
|
68
|
+
|
69
|
+
except Exception as e:
|
70
|
+
raise ValueError("Erro na inicialização da classe:", e)
|
71
|
+
|
72
|
+
def select_one_element(self, target):
|
73
|
+
"""
|
74
|
+
Clica em um elemento na tela identificado pelo seletor fornecido.
|
75
|
+
Args:
|
76
|
+
target (str): O seletor XPATH do elemento a ser clicado.
|
77
|
+
timeout (int, opcional): O tempo máximo (em segundos) para aguardar
|
78
|
+
que o elemento esteja disponível e não esteja obsoleto.
|
79
|
+
O padrão é 10 segundos.
|
80
|
+
Returns:
|
81
|
+
dict: Um dicionário contendo:
|
82
|
+
- "success" (bool): Indica se a operação foi bem-sucedida.
|
83
|
+
- "error" (Exception ou None): A exceção capturada em caso de falha,
|
84
|
+
ou None se não houver erro.
|
85
|
+
- "details" (None): Reservado para informações adicionais,
|
86
|
+
atualmente sempre retorna None.
|
87
|
+
Raises:
|
88
|
+
Exception: Qualquer exceção capturada durante a execução será retornada
|
89
|
+
no campo "error" do dicionário de retorno.
|
90
|
+
"""
|
91
|
+
try:
|
92
|
+
element_click = self.web_bot.find_element(target, By.XPATH)
|
93
|
+
self.web_bot.wait_for_stale_element(
|
94
|
+
element=element_click, timeout=self.timeout
|
95
|
+
)
|
96
|
+
return {"success": True, "error": None, "element": element_click}
|
97
|
+
except NoSuchElementException:
|
98
|
+
return {
|
99
|
+
"success": False,
|
100
|
+
"error": f"Elemento com o seletor '{target}' não encontrado.",
|
101
|
+
}
|
102
|
+
except TimeoutException:
|
103
|
+
return {
|
104
|
+
"success": False,
|
105
|
+
"error": f"Tempo limite excedido ao tentar localizar o elemento com o seletor '{target}'.",
|
106
|
+
}
|
107
|
+
except Exception as e:
|
108
|
+
return {"success": False, "error": e}
|
109
|
+
|
110
|
+
def close_tab(self):
|
111
|
+
try:
|
112
|
+
"""
|
113
|
+
Fecha a aba atual do navegador.
|
114
|
+
Este método tenta fechar a aba ativa do navegador utilizando o método `close_tab` do WebBot.
|
115
|
+
Caso ocorra algum erro durante o processo, uma exceção será levantada com uma mensagem descritiva.
|
116
|
+
"""
|
117
|
+
self.web_bot.close_page()
|
118
|
+
return {"success": True, "error": None}
|
119
|
+
except WebDriverException as e:
|
120
|
+
return {"success": False, "error": f"Erro ao fechar a aba: {e}"}
|
121
|
+
except TimeoutException:
|
122
|
+
return {
|
123
|
+
"success": False,
|
124
|
+
"error": "Tempo limite excedido ao tentar fechar a aba.",
|
125
|
+
}
|
126
|
+
except Exception as e:
|
127
|
+
return {"success": False, "error": f"Erro ao fechar a aba: {e}"}
|
128
|
+
|
129
|
+
def select_elements(self, target):
|
130
|
+
"""
|
131
|
+
Clica em um elemento na tela identificado pelo seletor fornecido.
|
132
|
+
Args:
|
133
|
+
target (str): O seletor XPATH do elemento a ser clicado.
|
134
|
+
timeout (int, opcional): O tempo máximo (em segundos) para aguardar
|
135
|
+
que o elemento esteja disponível e não esteja obsoleto.
|
136
|
+
O padrão é 10 segundos.
|
137
|
+
Returns:
|
138
|
+
dict: Um dicionário contendo:
|
139
|
+
- "success" (bool): Indica se a operação foi bem-sucedida.
|
140
|
+
- "error" (Exception ou None): A exceção capturada em caso de falha,
|
141
|
+
ou None se não houver erro.
|
142
|
+
- "details" (None): Reservado para informações adicionais,
|
143
|
+
atualmente sempre retorna None.
|
144
|
+
Raises:
|
145
|
+
Exception: Qualquer exceção capturada durante a execução será retornada
|
146
|
+
no campo "error" do dicionário de retorno.
|
147
|
+
"""
|
148
|
+
try:
|
149
|
+
element_click = self.web_bot.find_elements(target, By.XPATH)
|
150
|
+
self.web_bot.wait_for_stale_element(
|
151
|
+
element=element_click, timeout=self.timeout
|
152
|
+
)
|
153
|
+
return {"success": True, "error": None, "element": element_click}
|
154
|
+
except NoSuchElementException:
|
155
|
+
return {
|
156
|
+
"success": False,
|
157
|
+
"error": f"Elemento com o seletor '{target}' não encontrado.",
|
158
|
+
}
|
159
|
+
except TimeoutException:
|
160
|
+
return {
|
161
|
+
"success": False,
|
162
|
+
"error": f"Tempo limite excedido ao tentar localizar o elemento com o seletor '{target}'.",
|
163
|
+
}
|
164
|
+
except Exception as e:
|
165
|
+
return {"success": False, "error": e}
|
166
|
+
|
167
|
+
def input_value(self, target: str, value: str, clear: bool = True):
|
168
|
+
"""
|
169
|
+
Insere um valor em um elemento da página web identificado pelo seletor XPath.
|
170
|
+
|
171
|
+
Args:
|
172
|
+
target (str): O seletor XPath do elemento onde o valor será inserido.
|
173
|
+
value (str): O valor a ser inserido no elemento.
|
174
|
+
clear (bool, opcional): Indica se o campo deve ser limpo antes de inserir o valor.
|
175
|
+
O padrão é True.
|
176
|
+
|
177
|
+
Returns:
|
178
|
+
dict: Um dicionário contendo:
|
179
|
+
- "success" (bool): Indica se a operação foi bem-sucedida.
|
180
|
+
- "details" (None): Reservado para informações adicionais (atualmente não utilizado).
|
181
|
+
- "error" (str ou Exception): Mensagem de erro ou exceção, caso ocorra.
|
182
|
+
|
183
|
+
Exceções Tratadas:
|
184
|
+
- NoSuchElementException: Lançada quando o elemento não é encontrado.
|
185
|
+
- TimeoutException: Lançada quando o tempo limite para localizar o elemento é excedido.
|
186
|
+
- Exception: Captura qualquer outra exceção que possa ocorrer.
|
187
|
+
|
188
|
+
"""
|
189
|
+
try:
|
190
|
+
element_input = self.web_bot.find_element(target, By.XPATH)
|
191
|
+
self.web_bot.wait_for_stale_element(
|
192
|
+
element=element_input, timeout=self.timeout
|
193
|
+
)
|
194
|
+
if clear:
|
195
|
+
element_input.clear()
|
196
|
+
element_input.send_keys(value)
|
197
|
+
return {"success": True, "error": None}
|
198
|
+
except NoSuchElementException:
|
199
|
+
return {
|
200
|
+
"success": False,
|
201
|
+
"details": None,
|
202
|
+
"error": f"Elemento com o seletor '{target}' não encontrado.",
|
203
|
+
}
|
204
|
+
except TimeoutException:
|
205
|
+
return {
|
206
|
+
"success": False,
|
207
|
+
"details": None,
|
208
|
+
"error": f"Tempo limite excedido ao tentar localizar o elemento com o seletor '{target}'.",
|
209
|
+
}
|
210
|
+
except Exception as e:
|
211
|
+
return {"success": False, "details": None, "error": e}
|
212
|
+
|
213
|
+
def select_value(self, target: str, value: str):
|
214
|
+
"""
|
215
|
+
Seleciona um valor em um elemento do tipo <select> na página da web.
|
216
|
+
|
217
|
+
Args:
|
218
|
+
target (str): O seletor XPath do elemento <select> que será manipulado.
|
219
|
+
value (str): O valor que será selecionado no elemento <select>.
|
220
|
+
|
221
|
+
Returns:
|
222
|
+
dict: Um dicionário contendo:
|
223
|
+
- "success" (bool): Indica se a operação foi bem-sucedida.
|
224
|
+
- "details" (None): Reservado para informações adicionais (atualmente não utilizado).
|
225
|
+
- "error" (str ou Exception): Mensagem de erro em caso de falha ou a exceção capturada.
|
226
|
+
|
227
|
+
Exceções Tratadas:
|
228
|
+
- NoSuchElementException: Lançada quando o elemento com o seletor especificado não é encontrado.
|
229
|
+
- TimeoutException: Lançada quando o tempo limite para localizar o elemento é excedido.
|
230
|
+
- Exception: Captura qualquer outra exceção inesperada.
|
231
|
+
|
232
|
+
Observação:
|
233
|
+
Certifique-se de que o elemento identificado pelo seletor seja um elemento <select> válido.
|
234
|
+
"""
|
235
|
+
try:
|
236
|
+
element_select = self.web_bot.find_element(target, By.XPATH)
|
237
|
+
self.web_bot.wait_for_stale_element(
|
238
|
+
element=element_select, timeout=self.timeout
|
239
|
+
)
|
240
|
+
element_select = element_as_select(element_select)
|
241
|
+
element_select.select_by_value(value)
|
242
|
+
return {"success": True, "error": None}
|
243
|
+
except NoSuchElementException:
|
244
|
+
return {
|
245
|
+
"success": False,
|
246
|
+
"details": None,
|
247
|
+
"error": f"Elemento com o seletor '{target}' não encontrado.",
|
248
|
+
}
|
249
|
+
except TimeoutException:
|
250
|
+
return {
|
251
|
+
"success": False,
|
252
|
+
"details": None,
|
253
|
+
"error": f"Tempo limite excedido ao tentar localizar o elemento com o seletor '{target}'.",
|
254
|
+
}
|
255
|
+
except Exception as e:
|
256
|
+
return {"success": False, "details": None, "error": e}
|
257
|
+
|
258
|
+
def get_driver(self):
|
259
|
+
"""
|
260
|
+
Retorna a instância do driver web associada ao bot.
|
261
|
+
|
262
|
+
Returns:
|
263
|
+
WebDriver: A instância do driver web utilizada pelo bot.
|
264
|
+
"""
|
265
|
+
return self.web_bot
|
266
|
+
|
267
|
+
def change_tab(self, tab_index: int):
|
268
|
+
try:
|
269
|
+
"""
|
270
|
+
Altera para a aba especificada pelo índice.
|
271
|
+
Args:
|
272
|
+
tab_index (int): Índice da aba para a qual mudar (0 para a primeira aba).
|
273
|
+
Raises:
|
274
|
+
IndexError: Se o índice fornecido não corresponder a uma aba existente.
|
275
|
+
Exception: Para outros erros que possam ocorrer ao tentar mudar de aba.
|
276
|
+
"""
|
277
|
+
self.web_bot.activate_tab(tab_index)
|
278
|
+
return {"success": True, "error": None}
|
279
|
+
except IndexError:
|
280
|
+
return {
|
281
|
+
"success": False,
|
282
|
+
"error": f"A aba com índice {tab_index} não existe.",
|
283
|
+
}
|
284
|
+
except Exception as e:
|
285
|
+
return {"success": False, "error": f"Erro ao mudar de aba: {e}"}
|
@@ -0,0 +1,350 @@
|
|
1
|
+
import time
|
2
|
+
|
3
|
+
# Selenium
|
4
|
+
from selenium import webdriver
|
5
|
+
from selenium.webdriver.common.by import By
|
6
|
+
from selenium.webdriver.common.keys import Keys
|
7
|
+
from webdriver_manager.chrome import ChromeDriverManager
|
8
|
+
from selenium.webdriver.support.ui import WebDriverWait
|
9
|
+
from selenium.webdriver.common.action_chains import ActionChains
|
10
|
+
from selenium.webdriver.support import expected_conditions as EC
|
11
|
+
from selenium.common.exceptions import (
|
12
|
+
TimeoutException,
|
13
|
+
WebDriverException,
|
14
|
+
NoSuchElementException,
|
15
|
+
)
|
16
|
+
from selenium.webdriver.chrome.options import Options
|
17
|
+
from .web_screen_abstract import WebScreenAbstract
|
18
|
+
|
19
|
+
|
20
|
+
class WebScreenSelenium(WebScreenAbstract):
|
21
|
+
"""
|
22
|
+
Classe que implementa a interface WebScreenAbstract usando Selenium.
|
23
|
+
Métodos:
|
24
|
+
configuracao_inicial():
|
25
|
+
Configura o ambiente inicial para interações com a tela web usando Selenium.
|
26
|
+
click_on_screen(target: str, timeout: int = 10):
|
27
|
+
Clica em um elemento na tela web usando Selenium.
|
28
|
+
input_value(target: str, value: str, clear: bool = True):
|
29
|
+
Insere um valor em um campo de entrada na tela web usando Selenium.
|
30
|
+
select_value(target: str, value: str):
|
31
|
+
Seleciona um valor em um campo de seleção na tela web usando Selenium.
|
32
|
+
"""
|
33
|
+
|
34
|
+
def __init__(
|
35
|
+
self,
|
36
|
+
headless: bool = True,
|
37
|
+
disable_gpu: bool = True,
|
38
|
+
no_sandbox: bool = True,
|
39
|
+
timeout: int = 10,
|
40
|
+
security: bool = False,
|
41
|
+
scale: float = 0.8,
|
42
|
+
):
|
43
|
+
"""
|
44
|
+
Inicializa a classe responsável por configurar e gerenciar o WebDriver do Selenium.
|
45
|
+
|
46
|
+
Args:
|
47
|
+
headless (bool, opcional): Define se o navegador será executado em modo headless (sem interface gráfica).
|
48
|
+
Padrão é True.
|
49
|
+
disable_gpu (bool, opcional): Define se a GPU será desativada durante a execução do navegador.
|
50
|
+
Padrão é True.
|
51
|
+
no_sandbox (bool, opcional): Define se o navegador será executado sem o modo sandbox.
|
52
|
+
Padrão é True.
|
53
|
+
timeout (int, opcional): Tempo limite (em segundos) para operações do WebDriver.
|
54
|
+
Padrão é 10.
|
55
|
+
security (bool, opcional): Define se configurações adicionais de segurança serão aplicadas.
|
56
|
+
Padrão é False.
|
57
|
+
scale (float, opcional): Define o fator de escala da interface do navegador.
|
58
|
+
Deve ser um número positivo. Padrão é 0.8.
|
59
|
+
|
60
|
+
Raises:
|
61
|
+
ValueError: Caso os parâmetros fornecidos sejam inválidos.
|
62
|
+
ModuleNotFoundError: Caso o módulo Selenium não esteja instalado.
|
63
|
+
WebDriverException: Caso ocorra um erro ao inicializar o WebDriver do Selenium.
|
64
|
+
Exception: Para outros erros durante a inicialização da classe.
|
65
|
+
"""
|
66
|
+
if not isinstance(scale, (int, float)) or scale <= 0:
|
67
|
+
raise ValueError("O parâmetro 'scale' deve ser um número positivo.")
|
68
|
+
if not isinstance(headless, bool):
|
69
|
+
raise ValueError("O parâmetro 'headless' deve ser um booleano.")
|
70
|
+
if not isinstance(disable_gpu, bool):
|
71
|
+
raise ValueError("O parâmetro 'disable_gpu' deve ser um booleano.")
|
72
|
+
if not isinstance(no_sandbox, bool):
|
73
|
+
raise ValueError("O parâmetro 'no_sandbox' deve ser um booleano.")
|
74
|
+
if not isinstance(timeout, int) or timeout <= 0:
|
75
|
+
raise ValueError(
|
76
|
+
"O parâmetro 'timeout' deve ser um número inteiro positivo."
|
77
|
+
)
|
78
|
+
if not isinstance(security, bool):
|
79
|
+
raise ValueError("O parâmetro 'security' deve ser um booleano.")
|
80
|
+
|
81
|
+
self.driver = None
|
82
|
+
self.timeout = timeout
|
83
|
+
self.security = security
|
84
|
+
self.screenshot = []
|
85
|
+
try:
|
86
|
+
|
87
|
+
chrome_options = Options()
|
88
|
+
|
89
|
+
if headless:
|
90
|
+
chrome_options.add_argument("--headless")
|
91
|
+
if disable_gpu:
|
92
|
+
chrome_options.add_argument("--disable-gpu")
|
93
|
+
if no_sandbox:
|
94
|
+
chrome_options.add_argument("--no-sandbox")
|
95
|
+
chrome_options.add_argument("--disable-popup-blocking")
|
96
|
+
chrome_options.add_argument("--disable-extensions")
|
97
|
+
chrome_options.add_argument("--window-size=1920,1080")
|
98
|
+
chrome_options.add_argument(f"--force-device-scale-factor={scale}")
|
99
|
+
|
100
|
+
chrome_options.add_argument(
|
101
|
+
"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
|
102
|
+
)
|
103
|
+
|
104
|
+
self.driver = webdriver.Chrome(options=chrome_options)
|
105
|
+
self.driver.maximize_window()
|
106
|
+
self.driver.implicitly_wait(20)
|
107
|
+
|
108
|
+
except ModuleNotFoundError:
|
109
|
+
raise ModuleNotFoundError(
|
110
|
+
"O módulo Selenium não está instalado. Por favor, instale-o usando 'pip install selenium'."
|
111
|
+
)
|
112
|
+
except WebDriverException:
|
113
|
+
raise WebDriverException(
|
114
|
+
"Erro ao inicializar o WebDriver do Selenium. Verifique se o ChromeDriver está instalado e configurado corretamente."
|
115
|
+
)
|
116
|
+
except Exception as e:
|
117
|
+
raise Exception("Erro na inicialização da classe:", e)
|
118
|
+
|
119
|
+
def select_one_element(
|
120
|
+
self,
|
121
|
+
target: str,
|
122
|
+
time: int = 15,
|
123
|
+
webdrive_type: str = "visibilidade_do_elemento",
|
124
|
+
):
|
125
|
+
"""
|
126
|
+
Seleciona um único elemento na página da web com base no XPath fornecido.
|
127
|
+
Args:
|
128
|
+
target (str): O XPath do elemento a ser localizado.
|
129
|
+
time (int, opcional): O tempo máximo (em segundos) para aguardar o elemento.
|
130
|
+
O padrão é 15 segundos.
|
131
|
+
webdrive_type (str, opcional): O tipo de condição de espera para localizar o elemento.
|
132
|
+
Pode ser "elemento_clicavel" para aguardar que o elemento seja clicável ou
|
133
|
+
"visibilidade_do_elemento" para aguardar que o elemento esteja visível.
|
134
|
+
O padrão é "visibilidade_do_elemento".
|
135
|
+
Returns:
|
136
|
+
WebElement: O elemento localizado.
|
137
|
+
Raises:
|
138
|
+
TimeoutError: Se o tempo de espera for excedido e o elemento não for localizado.
|
139
|
+
Exception: Para qualquer outro erro inesperado ao localizar o elemento.
|
140
|
+
"""
|
141
|
+
webdrive_map = {
|
142
|
+
"elemento_clicavel": EC.element_to_be_clickable,
|
143
|
+
"visibilidade_do_elemento": EC.visibility_of_element_located,
|
144
|
+
}
|
145
|
+
try:
|
146
|
+
element = WebDriverWait(self.driver, time).until(
|
147
|
+
webdrive_map.get(webdrive_type, EC.visibility_of_element_located)(
|
148
|
+
(By.XPATH, target)
|
149
|
+
)
|
150
|
+
)
|
151
|
+
return {"success": True, "element": element, "erro": None}
|
152
|
+
except TimeoutException as e:
|
153
|
+
return {"success": False, "element": None, "erro": e}
|
154
|
+
except Exception as e:
|
155
|
+
return {"success": False, "element": None, "erro": e}
|
156
|
+
|
157
|
+
def select_elements(
|
158
|
+
self,
|
159
|
+
target: str,
|
160
|
+
time: int = 15,
|
161
|
+
):
|
162
|
+
"""
|
163
|
+
Seleciona múltiplos elementos na página utilizando um XPath.
|
164
|
+
Args:
|
165
|
+
target (str): O XPath dos elementos a serem localizados.
|
166
|
+
time (int, opcional): O tempo máximo de espera (em segundos) para localizar os elementos.
|
167
|
+
O padrão é 15 segundos.
|
168
|
+
Returns:
|
169
|
+
list: Uma lista de elementos Web encontrados pelo XPath.
|
170
|
+
Raises:
|
171
|
+
Exception: Lança uma exceção se ocorrer um erro ao buscar os elementos.
|
172
|
+
"""
|
173
|
+
try:
|
174
|
+
element = WebDriverWait(self.driver, time).until(
|
175
|
+
lambda driver: driver.find_elements(By.XPATH, target)
|
176
|
+
)
|
177
|
+
return {"success": True, "elements": element, "erro": None}
|
178
|
+
except Exception as e:
|
179
|
+
return {"success": False, "elements": None, "erro": e}
|
180
|
+
|
181
|
+
def close_tab(self):
|
182
|
+
"""
|
183
|
+
Fecha a aba atual do navegador.
|
184
|
+
|
185
|
+
Este método tenta fechar a aba ativa do navegador utilizando o driver Selenium.
|
186
|
+
Caso ocorra algum erro durante o processo, uma exceção será levantada com uma
|
187
|
+
mensagem descritiva.
|
188
|
+
|
189
|
+
Raises:
|
190
|
+
Exception: Caso ocorra um erro ao tentar fechar a aba, uma exceção será
|
191
|
+
levantada contendo detalhes do erro.
|
192
|
+
"""
|
193
|
+
try:
|
194
|
+
self.driver.close()
|
195
|
+
return {"success": True, "erro": None, "element": None}
|
196
|
+
except Exception as e:
|
197
|
+
return {"success": False, "erro": e, "element": None}
|
198
|
+
|
199
|
+
def get_driver(self):
|
200
|
+
"""
|
201
|
+
Retorna o driver da instância atual.
|
202
|
+
|
203
|
+
Returns:
|
204
|
+
WebDriver: O driver associado a esta instância.
|
205
|
+
"""
|
206
|
+
return {"success": True, "erro": None, "driver": self.driver}
|
207
|
+
|
208
|
+
def change_tab(self, tab_index: int):
|
209
|
+
"""
|
210
|
+
Args:
|
211
|
+
tab_index (int): Índice da aba para a qual mudar (0 para a primeira aba).
|
212
|
+
|
213
|
+
Raises:
|
214
|
+
IndexError: Se o índice fornecido não corresponder a uma aba existente.
|
215
|
+
Exception: Para outros erros que possam ocorrer ao tentar mudar de aba.
|
216
|
+
Altera para a aba especificada pelo índice.
|
217
|
+
:param tab_index: Índice da aba para a qual mudar (0 para a primeira aba).
|
218
|
+
"""
|
219
|
+
try:
|
220
|
+
self.driver.switch_to.window(self.driver.window_handles[tab_index])
|
221
|
+
return {"success": True, "erro": None, "element": None}
|
222
|
+
except IndexError as e:
|
223
|
+
return {"success": False, "erro": e, "element": None}
|
224
|
+
except Exception as e:
|
225
|
+
return {"success": False, "erro": e, "element": None}
|
226
|
+
|
227
|
+
def execute_script(self, script: str, *args):
|
228
|
+
"""
|
229
|
+
Executa um script JavaScript na aba atual.
|
230
|
+
:param script: O script JavaScript a ser executado.
|
231
|
+
"""
|
232
|
+
try:
|
233
|
+
self.driver.execute_script(script, *args)
|
234
|
+
return {"success": True, "erro": None, "element": None}
|
235
|
+
except Exception as e:
|
236
|
+
return {"success": False, "erro": e, "element": None}
|
237
|
+
|
238
|
+
def scroll_until_element_found(
|
239
|
+
self,
|
240
|
+
target: str,
|
241
|
+
max_scrolls: int = 20,
|
242
|
+
scroll_pause_time: int = 1,
|
243
|
+
):
|
244
|
+
"""
|
245
|
+
Rola a página até que um elemento seja encontrado ou o número máximo de rolagens seja atingido.
|
246
|
+
|
247
|
+
Args:
|
248
|
+
target (str): O XPath do elemento alvo que deve ser encontrado.
|
249
|
+
max_scrolls (int, opcional): O número máximo de rolagens permitidas. Padrão é 20.
|
250
|
+
scroll_pause_time (int, opcional): O tempo de pausa (em segundos) entre cada rolagem. Padrão é 1.
|
251
|
+
|
252
|
+
Returns:
|
253
|
+
WebElement: O elemento encontrado correspondente ao XPath fornecido.
|
254
|
+
|
255
|
+
Raises:
|
256
|
+
Exception: Se o elemento não for encontrado após o número máximo de rolagens.
|
257
|
+
"""
|
258
|
+
for _ in range(max_scrolls):
|
259
|
+
try:
|
260
|
+
element = self.driver.find_element(By.XPATH, target)
|
261
|
+
ActionChains(self.driver).move_to_element(element).perform()
|
262
|
+
return {"success": True, "element": element, "erro": None}
|
263
|
+
except NoSuchElementException:
|
264
|
+
self.driver.execute_script("window.scrollBy(0, window.innerHeight);")
|
265
|
+
time.sleep(scroll_pause_time)
|
266
|
+
return {
|
267
|
+
"success": False,
|
268
|
+
"element": None,
|
269
|
+
"erro": f"Elemento com o xpath '{target}' não encontrado após {max_scrolls} rolagens.",
|
270
|
+
}
|
271
|
+
|
272
|
+
def scroll_virtuallist_until_element_found(
|
273
|
+
self,
|
274
|
+
list_target: str,
|
275
|
+
target: str,
|
276
|
+
max_scrolls: int = 20,
|
277
|
+
scroll_pause_time: int = 0.2,
|
278
|
+
):
|
279
|
+
"""
|
280
|
+
Rola uma lista virtual até que um elemento específico seja encontrado.
|
281
|
+
Este método tenta localizar um elemento em uma lista virtual rolando-a para baixo
|
282
|
+
até que o elemento seja encontrado ou até que o número máximo de rolagens seja atingido.
|
283
|
+
Args:
|
284
|
+
list_target (str): O alvo da lista virtual que será rolada.
|
285
|
+
target (str): O XPath do elemento que se deseja localizar.
|
286
|
+
max_scrolls (int, opcional): O número máximo de rolagens permitidas. Padrão é 20.
|
287
|
+
scroll_pause_time (int, opcional): O tempo de pausa (em segundos) entre as rolagens. Padrão é 0.2.
|
288
|
+
Returns:
|
289
|
+
WebElement: O elemento encontrado.
|
290
|
+
Raises:
|
291
|
+
Exception: Se o elemento não for encontrado após o número máximo de rolagens.
|
292
|
+
"""
|
293
|
+
for _ in range(max_scrolls):
|
294
|
+
try:
|
295
|
+
element = self.driver.find_element(By.XPATH, target)
|
296
|
+
return {"success": True, "element": element, "erro": None}
|
297
|
+
except NoSuchElementException:
|
298
|
+
for _ in range(10):
|
299
|
+
list_target.send_keys(Keys.ARROW_DOWN)
|
300
|
+
time.sleep(0.1)
|
301
|
+
time.sleep(scroll_pause_time)
|
302
|
+
return {
|
303
|
+
"success": False,
|
304
|
+
"erro": f"Elemento com o xpath '{target}' não encontrado após {max_scrolls} rolagens.",
|
305
|
+
"element": None,
|
306
|
+
}
|
307
|
+
|
308
|
+
def refresh_page(self):
|
309
|
+
"""
|
310
|
+
Atualiza a página atual no navegador.
|
311
|
+
|
312
|
+
Este método tenta atualizar a página atual utilizando o método `refresh` do driver.
|
313
|
+
Caso ocorra algum erro durante o processo, uma exceção será levantada com uma mensagem
|
314
|
+
descritiva.
|
315
|
+
|
316
|
+
Raises:
|
317
|
+
Exception: Caso ocorra algum erro ao tentar atualizar a página, uma exceção será
|
318
|
+
levantada contendo a mensagem de erro original.
|
319
|
+
"""
|
320
|
+
try:
|
321
|
+
self.driver.refresh()
|
322
|
+
return {"success": True, "erro": None, "element": None}
|
323
|
+
except Exception as e:
|
324
|
+
return {"success": False, "erro": e, "element": None}
|
325
|
+
|
326
|
+
def save_screenshot(self, screenshot_path: str):
|
327
|
+
"""
|
328
|
+
Captura uma captura de tela da página atual.
|
329
|
+
|
330
|
+
Este método tenta capturar uma captura de tela da página atual utilizando o método `screenshot` do driver.
|
331
|
+
A captura de tela é salva em um arquivo temporário e o caminho do arquivo é retornado.
|
332
|
+
|
333
|
+
Returns:
|
334
|
+
str: O caminho do arquivo onde a captura de tela foi salva.
|
335
|
+
|
336
|
+
Raises:
|
337
|
+
Exception: Caso ocorra algum erro ao capturar a captura de tela, uma exceção será levantada.
|
338
|
+
"""
|
339
|
+
if not screenshot_path or not isinstance(screenshot_path, str):
|
340
|
+
return {
|
341
|
+
"success": False,
|
342
|
+
"erro": "O caminho para salvar a captura de tela deve ser uma string não vazia.",
|
343
|
+
"diretorio": None,
|
344
|
+
}
|
345
|
+
try:
|
346
|
+
screenshot_path = f"{screenshot_path}screenshot_{int(time.time())}.png"
|
347
|
+
self.driver.save_screenshot(screenshot_path)
|
348
|
+
return {"success": True, "erro": None, "diretorio": screenshot_path}
|
349
|
+
except Exception as e:
|
350
|
+
return {"success": False, "erro": e, "diretorio": None}
|
csc_cia_stne/web.py
CHANGED
@@ -1,30 +1,22 @@
|
|
1
|
-
# Selenium
|
2
|
-
from selenium import webdriver
|
3
|
-
from webdriver_manager.chrome import ChromeDriverManager
|
4
|
-
from selenium.webdriver.chrome.service import Service as ChromeService
|
5
|
-
from selenium.webdriver.chrome.options import Options
|
6
|
-
from selenium.webdriver.support.ui import Select,WebDriverWait
|
7
|
-
from selenium.webdriver.common.by import By
|
8
|
-
from selenium.webdriver.support import expected_conditions as EC
|
9
|
-
|
10
|
-
# Botcity
|
11
|
-
from botcity.web import WebBot, Browser
|
12
|
-
from botcity.web.util import element_as_select
|
13
|
-
|
14
|
-
# Externa
|
15
|
-
import requests
|
16
|
-
|
17
1
|
# Validador
|
18
2
|
from pydantic import ValidationError
|
19
3
|
|
20
4
|
# Validadores de parametros
|
21
|
-
from .utilitarios.validations.web_validator import InitParamsValidator
|
5
|
+
from .utilitarios.validations.web_validator import InitParamsValidator
|
6
|
+
from .utilitarios.web_screen import WebScreenSelenium, WebScreenBotCity
|
22
7
|
|
23
8
|
|
24
|
-
class web_screen
|
9
|
+
class web_screen:
|
25
10
|
|
26
|
-
|
27
|
-
|
11
|
+
def __init__(
|
12
|
+
self,
|
13
|
+
model: str = "selenium",
|
14
|
+
timeout: int = 60,
|
15
|
+
headless: bool = True,
|
16
|
+
disable_gpu: bool = True,
|
17
|
+
no_sandbox: bool = True,
|
18
|
+
security: bool = True,
|
19
|
+
):
|
28
20
|
"""
|
29
21
|
Inicializa a instância da classe Web.
|
30
22
|
Parâmetros:
|
@@ -37,477 +29,43 @@ class web_screen():
|
|
37
29
|
Raises:
|
38
30
|
- ValueError: Se ocorrer um erro na validação dos dados de entrada da inicialização da instância.
|
39
31
|
"""
|
40
|
-
|
32
|
+
|
41
33
|
self.model = model
|
42
34
|
self.timeout = timeout
|
43
35
|
self.security = security
|
44
|
-
|
45
|
-
try:
|
46
|
-
|
47
|
-
InitParamsValidator(model=model,timeout=timeout, headless=headless, disable_gpu=disable_gpu, no_sandbox=no_sandbox, security=security)
|
48
|
-
|
49
|
-
except ValidationError as e:
|
50
|
-
|
51
|
-
raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
|
52
|
-
|
53
|
-
if self.model.upper() == "SELENIUM":
|
54
|
-
|
55
|
-
try:
|
56
|
-
|
57
|
-
chrome_options = Options()
|
58
|
-
|
59
|
-
if headless:
|
60
|
-
chrome_options.add_argument('--headless')
|
61
|
-
if disable_gpu:
|
62
|
-
chrome_options.add_argument('--disable-gpu')
|
63
|
-
if no_sandbox:
|
64
|
-
chrome_options.add_argument('--no-sandbox')
|
65
|
-
|
66
|
-
# Criação do drive para selenium
|
67
|
-
service = ChromeService(executable_path=ChromeDriverManager().install())
|
68
|
-
|
69
|
-
self.web_bot = webdriver.Chrome(service=service, options=chrome_options)
|
70
|
-
|
71
|
-
except Exception as e:
|
72
|
-
|
73
|
-
raise ValueError("Erro na inicialização da classe:", e)
|
74
|
-
|
75
|
-
else:
|
76
|
-
|
77
|
-
try:
|
78
|
-
|
79
|
-
# Criação do drive para botcity
|
80
|
-
|
81
|
-
self.web_bot = WebBot()
|
82
|
-
|
83
|
-
# Configurar o navegador (por exemplo, Chrome)
|
84
|
-
self.web_bot.browser = Browser.CHROME
|
85
|
-
|
86
|
-
self.web_bot.driver_path = ChromeDriverManager().install()
|
87
|
-
|
88
|
-
# Configurar as opções do Chrome
|
89
|
-
self.web_bot.headless = headless
|
90
|
-
self.web_bot.disable_gpu = disable_gpu
|
91
|
-
self.web_bot.no_sandbox = no_sandbox
|
92
|
-
|
93
|
-
except Exception as e:
|
94
|
-
|
95
|
-
raise ValueError("Erro na inicialização da classe:", e)
|
96
|
-
|
97
|
-
|
98
|
-
def get_bot(self):
|
99
|
-
"""
|
100
|
-
Retorna o objeto web_bot associado a esta instância.
|
101
|
-
"""
|
102
|
-
|
103
|
-
return self.web_bot
|
104
|
-
|
105
|
-
|
106
|
-
def verify_server(self,url:str):
|
107
|
-
"""
|
108
|
-
Verifica se o servidor está ativo e acessível.
|
109
|
-
Args:
|
110
|
-
url (str): A URL do servidor a ser verificado.
|
111
|
-
Returns:
|
112
|
-
bool: True se o servidor estiver ativo e acessível, False caso contrário.
|
113
|
-
"""
|
114
|
-
|
115
|
-
try:
|
116
|
-
|
117
|
-
VerifyServerValueValidator(url=url)
|
118
|
-
|
119
|
-
except ValidationError as e:
|
120
|
-
|
121
|
-
raise ValueError("Erro na validação dos dados de input:", e.errors())
|
122
|
-
|
123
|
-
try:
|
124
|
-
|
125
|
-
reply = requests.get(url, verify=self.security)
|
126
|
-
|
127
|
-
except:
|
128
|
-
|
129
|
-
return False
|
130
|
-
|
131
|
-
if reply.status_code == 200:
|
132
|
-
|
133
|
-
return True
|
134
|
-
|
135
|
-
return False
|
136
|
-
|
137
|
-
|
138
|
-
def navigate(self,url:str):
|
139
|
-
"""
|
140
|
-
Navega para a URL especificada.
|
141
|
-
Args:
|
142
|
-
url (str): A URL para navegar.
|
143
|
-
Returns:
|
144
|
-
dict: Um dicionário contendo informações sobre o sucesso da navegação.
|
145
|
-
- 'success' (bool): Indica se a navegação foi bem-sucedida.
|
146
|
-
- 'details' (str): Detalhes adicionais sobre a navegação, caso haja algum erro.
|
147
|
-
- 'error' (Exception): A exceção ocorrida durante a navegação, caso haja algum erro.
|
148
|
-
"""
|
149
|
-
|
150
|
-
try:
|
151
|
-
|
152
|
-
NavigateValidator(url=url)
|
153
|
-
|
154
|
-
except ValidationError as e:
|
155
|
-
|
156
|
-
raise ValueError("Erro na validação dos dados de input:", e.errors())
|
157
|
-
|
158
|
-
if not self.verify_server(url):
|
159
|
-
|
160
|
-
return {
|
161
|
-
'success': False,
|
162
|
-
'details': f"Não foi possível acessar o endereço {url}."
|
163
|
-
}
|
164
|
-
|
165
|
-
if self.model.upper() == "SELENIUM":
|
166
|
-
|
167
|
-
try:
|
168
|
-
|
169
|
-
self.bot.get(url)
|
170
|
-
|
171
|
-
return {
|
172
|
-
"success": True,
|
173
|
-
"error": None
|
174
|
-
}
|
175
|
-
|
176
|
-
except Exception as e:
|
177
|
-
|
178
|
-
return {
|
179
|
-
"success": False,
|
180
|
-
"details":None,
|
181
|
-
"error": e
|
182
|
-
}
|
183
|
-
|
184
|
-
else:
|
185
|
-
|
186
|
-
try:
|
187
|
-
|
188
|
-
self.bot.browse(url)
|
189
|
-
|
190
|
-
return {
|
191
|
-
"success": True,
|
192
|
-
"error": None
|
193
|
-
}
|
194
|
-
|
195
|
-
except Exception as e:
|
196
|
-
|
197
|
-
return {
|
198
|
-
"success": False,
|
199
|
-
"details":None,
|
200
|
-
"error": e
|
201
|
-
}
|
202
|
-
|
203
|
-
|
204
|
-
def click_on_screen(self, target:str):
|
205
|
-
"""
|
206
|
-
Clica em um elemento na tela.
|
207
|
-
Parâmetros:
|
208
|
-
- target (str): O elemento alvo a ser clicado.
|
209
|
-
Retorna:
|
210
|
-
Um dicionário com as seguintes chaves:
|
211
|
-
- success (bool): Indica se o clique foi realizado com sucesso.
|
212
|
-
- details (str): Detalhes adicionais em caso de erro.
|
213
|
-
- error (Exception): A exceção ocorrida, se houver.
|
214
|
-
Raises:
|
215
|
-
Nenhum.
|
216
|
-
"""
|
217
|
-
|
218
|
-
try:
|
219
|
-
|
220
|
-
ClickOnScreenValidator(target=target)
|
221
|
-
|
222
|
-
except ValidationError as e:
|
223
|
-
|
224
|
-
raise ValueError("Erro na validação dos dados de input para o click na tela:", e.errors())
|
225
|
-
|
226
|
-
|
227
|
-
if self.model.upper() == "SELENIUM":
|
228
|
-
|
229
|
-
try:
|
230
|
-
|
231
|
-
WebDriverWait(self.web_bot, self.timeout).until(EC.element_to_be_clickable((By.XPATH, target))).click()
|
232
|
-
|
233
|
-
return {
|
234
|
-
"success": True,
|
235
|
-
"error": None
|
236
|
-
}
|
237
|
-
|
238
|
-
except EC.NoSuchElementException:
|
239
|
-
|
240
|
-
return {
|
241
|
-
"success": False,
|
242
|
-
"details": f"Elemento {target} não encontrado.",
|
243
|
-
"error": None
|
244
|
-
}
|
245
|
-
|
246
|
-
except EC.TimeoutException:
|
247
|
-
|
248
|
-
return {
|
249
|
-
"success": False,
|
250
|
-
"details": f"O elemento {target} não foi encontrado dentro do tempo definido",
|
251
|
-
"error": None
|
252
|
-
}
|
253
|
-
|
254
|
-
except Exception as e:
|
255
|
-
|
256
|
-
return {
|
257
|
-
"success": False,
|
258
|
-
"details":None,
|
259
|
-
"error": e
|
260
|
-
}
|
261
|
-
|
262
|
-
else:
|
263
|
-
|
264
|
-
try:
|
265
|
-
|
266
|
-
element_click = self.web_bot.find_element(target, By.XPATH)
|
267
|
-
|
268
|
-
self.web_bot.wait_for_stale_element(
|
269
|
-
element=element_click,
|
270
|
-
timeout=self.timeout
|
271
|
-
)
|
272
|
-
|
273
|
-
element_click.click()
|
274
|
-
|
275
|
-
return {
|
276
|
-
"success": True,
|
277
|
-
"error": None
|
278
|
-
}
|
279
|
-
|
280
|
-
except Exception as e:
|
281
|
-
|
282
|
-
return {
|
283
|
-
"success": False,
|
284
|
-
"details": None,
|
285
|
-
"error": e
|
286
|
-
}
|
287
|
-
|
288
|
-
|
289
|
-
def input_value(self, target:str, value, clear:bool=True):
|
290
|
-
"""
|
291
|
-
Insere um valor em um elemento de entrada na página web.
|
292
|
-
Parâmetros:
|
293
|
-
- target (str): O XPath do elemento de entrada.
|
294
|
-
- value: O valor a ser inserido no elemento de entrada.
|
295
|
-
- clear (bool): Indica se o elemento de entrada deve ser limpo antes de inserir o valor (padrão: True).
|
296
|
-
Retorna:
|
297
|
-
Um dicionário com as seguintes chaves:
|
298
|
-
- "success" (bool): Indica se a operação foi bem-sucedida.
|
299
|
-
- "details" (str): Detalhes adicionais sobre o resultado da operação.
|
300
|
-
- "error" (Exception): A exceção ocorrida, se houver.
|
301
|
-
"""
|
302
|
-
|
36
|
+
self.driver = None
|
303
37
|
try:
|
304
|
-
|
305
|
-
InputValueValidator(target=target,clear=clear)
|
306
|
-
|
307
|
-
except ValidationError as e:
|
308
|
-
|
309
|
-
raise ValueError("Erro na validação dos dados de input para realizar o input na tela:", e.errors())
|
310
|
-
|
311
|
-
if self.model.upper() == "SELENIUM":
|
312
|
-
|
313
|
-
try:
|
314
|
-
|
315
|
-
element_input = WebDriverWait(self.web_bot, self.timeout).until(EC.EC.visibility_of_element_located(By.XPATH,target))
|
316
|
-
|
317
|
-
if clear:
|
318
|
-
|
319
|
-
element_input.clear()
|
320
|
-
|
321
|
-
element_input.send_keys(value)
|
322
|
-
|
323
|
-
except EC.NoSuchElementException:
|
324
|
-
|
325
|
-
return {
|
326
|
-
"success": False,
|
327
|
-
"details": f"Elemento {target} não encontrado.",
|
328
|
-
"error": None
|
329
|
-
}
|
330
|
-
|
331
|
-
except EC.TimeoutException:
|
332
|
-
|
333
|
-
return {
|
334
|
-
"success": False,
|
335
|
-
"details": f"O elemento {target} não foi encontrado dentro do tempo definido",
|
336
|
-
"error": None
|
337
|
-
}
|
338
|
-
|
339
|
-
except Exception as e:
|
340
|
-
|
341
|
-
return {
|
342
|
-
"success": False,
|
343
|
-
"details":None,
|
344
|
-
"error": e
|
345
|
-
}
|
346
|
-
|
347
|
-
else:
|
348
|
-
|
349
|
-
try:
|
350
|
-
|
351
|
-
element_input = self.web_bot.find_element(target, By.XPATH)
|
352
|
-
|
353
|
-
self.web_bot.wait_for_stale_element(
|
354
|
-
element=element_input,
|
355
|
-
timeout=self.timeout
|
356
|
-
)
|
357
|
-
|
358
|
-
if clear:
|
359
38
|
|
360
|
-
|
361
|
-
|
362
|
-
|
363
|
-
|
364
|
-
|
365
|
-
|
366
|
-
|
367
|
-
|
368
|
-
"details":None,
|
369
|
-
"error": e
|
370
|
-
}
|
371
|
-
|
372
|
-
|
373
|
-
def select_value(self, target:str, value):
|
374
|
-
"""
|
375
|
-
Seleciona um valor em um elemento de seleção (select) na página web.
|
376
|
-
Args:
|
377
|
-
target (str): O seletor XPath do elemento de seleção.
|
378
|
-
value: O valor a ser selecionado.
|
379
|
-
Returns:
|
380
|
-
dict: Um dicionário com as seguintes chaves:
|
381
|
-
- "success" (bool): Indica se a seleção foi bem-sucedida.
|
382
|
-
- "details" (str): Detalhes adicionais sobre o resultado da seleção.
|
383
|
-
- "error" (Exception): A exceção ocorrida, se houver.
|
384
|
-
Raises:
|
385
|
-
ValueError: Se ocorrer um erro na validação dos dados para realizar o select na tela.
|
386
|
-
Note:
|
387
|
-
- Se o modelo for "SELENIUM", o método usará a biblioteca Selenium para realizar a seleção.
|
388
|
-
- Caso contrário, o método usará a biblioteca web_bot para realizar a seleção.
|
389
|
-
"""
|
390
|
-
|
391
|
-
try:
|
392
|
-
|
393
|
-
SelectValueValidator(target=target)
|
39
|
+
InitParamsValidator(
|
40
|
+
model=model,
|
41
|
+
timeout=timeout,
|
42
|
+
headless=headless,
|
43
|
+
disable_gpu=disable_gpu,
|
44
|
+
no_sandbox=no_sandbox,
|
45
|
+
security=security,
|
46
|
+
)
|
394
47
|
|
395
48
|
except ValidationError as e:
|
396
|
-
|
397
|
-
raise ValueError("Erro na validação dos dados para realizar o select na tela:", e.errors())
|
398
|
-
|
399
|
-
if self.model.upper() == "SELENIUM":
|
400
|
-
|
401
|
-
try:
|
402
|
-
|
403
|
-
element_select = WebDriverWait(self.web_bot, self.timeout).until(EC.element_to_be_clickable((By.XPATH, target)))
|
404
|
-
|
405
|
-
element_select = Select(element_select)
|
406
|
-
|
407
|
-
element_select.select_by_value(value)
|
408
|
-
|
409
|
-
except EC.NoSuchElementException:
|
410
|
-
|
411
|
-
return {
|
412
|
-
"success": False,
|
413
|
-
"details": f"Elemento {target} não encontrado.",
|
414
|
-
"error": None
|
415
|
-
}
|
416
|
-
|
417
|
-
except EC.TimeoutException:
|
418
|
-
|
419
|
-
return {
|
420
|
-
"success": False,
|
421
|
-
"details": f"O elemento {target} não foi encontrado dentro do tempo definido",
|
422
|
-
"error": None
|
423
|
-
}
|
424
|
-
|
425
|
-
except Exception as e:
|
426
|
-
|
427
|
-
return {
|
428
|
-
"success": False,
|
429
|
-
"details":None,
|
430
|
-
"error": e
|
431
|
-
}
|
432
|
-
|
433
|
-
else:
|
434
|
-
|
435
|
-
try:
|
436
|
-
|
437
|
-
element_select = self.web_bot.find_element(target, By.XPATH)
|
438
|
-
|
439
|
-
self.web_bot.wait_for_stale_element(
|
440
|
-
element=element_select,
|
441
|
-
timeout=self.timeout
|
442
|
-
)
|
443
|
-
|
444
|
-
element_select = element_as_select(element_select)
|
445
|
-
|
446
|
-
element_select.select_by_value(value)
|
447
|
-
|
448
|
-
except Exception as e:
|
449
|
-
|
450
|
-
return {
|
451
|
-
"success": False,
|
452
|
-
"details":None,
|
453
|
-
"error": e
|
454
|
-
}
|
455
|
-
|
456
|
-
|
457
|
-
def close(self):
|
458
|
-
"""
|
459
|
-
Fecha o navegador web.
|
460
|
-
Retorna um dicionário com as seguintes chaves:
|
461
|
-
- 'success': Indica se o fechamento foi bem-sucedido (True) ou não (False).
|
462
|
-
- 'details': Detalhes adicionais, caso ocorra algum erro durante o fechamento.
|
463
|
-
- 'error': Exceção ocorrida durante o fechamento, caso haja.
|
464
|
-
Se o modelo for 'SELENIUM', o método utiliza o método 'quit()' do objeto 'web_bot' para fechar o navegador.
|
465
|
-
Caso contrário, utiliza o método 'stop_browser()'.
|
466
|
-
Exemplo de retorno em caso de sucesso:
|
467
|
-
{
|
468
|
-
'success': True,
|
469
|
-
'error': None
|
470
|
-
Exemplo de retorno em caso de erro:
|
471
|
-
{
|
472
|
-
'success': False,
|
473
|
-
'details': None,
|
474
|
-
'error': Exception
|
475
|
-
"""
|
476
|
-
|
477
|
-
if self.model.upper() == "SELENIUM":
|
478
|
-
|
479
|
-
try:
|
480
|
-
|
481
|
-
self.web_bot.quit()
|
482
|
-
|
483
|
-
return {
|
484
|
-
"success": True,
|
485
|
-
"error": None
|
486
|
-
}
|
487
|
-
|
488
|
-
except Exception as e:
|
489
|
-
|
490
|
-
return {
|
491
|
-
"success": False,
|
492
|
-
"details": None,
|
493
|
-
"error": e
|
494
|
-
}
|
495
|
-
|
496
|
-
else:
|
497
|
-
|
498
|
-
try:
|
499
|
-
|
500
|
-
self.web_bot.stop_browser()
|
501
|
-
|
502
|
-
return {
|
503
|
-
"success": True,
|
504
|
-
"error": None
|
505
|
-
}
|
506
|
-
|
507
|
-
except Exception as e:
|
508
49
|
|
509
|
-
|
510
|
-
|
511
|
-
|
512
|
-
|
513
|
-
|
50
|
+
raise ValueError(
|
51
|
+
"Erro na validação dos dados de input da inicialização da instância:",
|
52
|
+
e.errors(),
|
53
|
+
)
|
54
|
+
|
55
|
+
self.instancia = (
|
56
|
+
WebScreenSelenium(
|
57
|
+
headless=headless,
|
58
|
+
disable_gpu=disable_gpu,
|
59
|
+
no_sandbox=no_sandbox,
|
60
|
+
timeout=timeout,
|
61
|
+
security=security,
|
62
|
+
)
|
63
|
+
if model.upper() == "SELENIUM"
|
64
|
+
else WebScreenBotCity(
|
65
|
+
headless=headless,
|
66
|
+
disable_gpu=disable_gpu,
|
67
|
+
no_sandbox=no_sandbox,
|
68
|
+
timeout=timeout,
|
69
|
+
security=security,
|
70
|
+
)
|
71
|
+
)
|
@@ -14,13 +14,13 @@ csc_cia_stne/servicenow.py,sha256=cJtNtLZ8glWfs3OAzl78ZFlPyPz39CSBxHqpTdUU7i0,32
|
|
14
14
|
csc_cia_stne/slack.py,sha256=sPLeaQh_JewLcrBDjjwUgbjtC7d1Np03OTy06JimMV4,8117
|
15
15
|
csc_cia_stne/stne_admin.py,sha256=4v_BVQAwZeWmxvjDOkwFAl9yIxJ3r54BY7pRgAgSXEM,24220
|
16
16
|
csc_cia_stne/wacess.py,sha256=g-bWZNpm_tU7UsW1G_rqh_2fW2KShvxZHGOerX8DuQw,26768
|
17
|
-
csc_cia_stne/web.py,sha256=
|
17
|
+
csc_cia_stne/web.py,sha256=g1T6GKfCZ77uRfzkHc_MGz8shUhyZ-VUIWdvAjQFk-Y,2377
|
18
18
|
csc_cia_stne/utilitarios/__init__.py,sha256=eUaRttjY-F_zHAHC3L22VZxWyQd_k9zso-Mjz01Rj9o,306
|
19
19
|
csc_cia_stne/utilitarios/functions/__init__.py,sha256=tBN1a6ZlvS1kLXIGopaqecJvlkOhLvLeYjp3JCAspWs,471
|
20
20
|
csc_cia_stne/utilitarios/functions/func_b64.py,sha256=XGU34BIQQXWXBS0yM2B4A2wDlcrMl1unIJXjq4lpLnk,1254
|
21
21
|
csc_cia_stne/utilitarios/functions/func_converters.py,sha256=EY1zvlBaRX7G1MceVSiRXwwKDQDZwUO9iECBL0fe5iU,481
|
22
22
|
csc_cia_stne/utilitarios/functions/func_datetime.py,sha256=UA7ch4sQWTiYcz8r6LtGujIdpTU-Sht8qmTYvm9vhh0,257
|
23
|
-
csc_cia_stne/utilitarios/functions/func_get_secret.py,sha256=
|
23
|
+
csc_cia_stne/utilitarios/functions/func_get_secret.py,sha256=XFsAd9GnKnf9WLnARqNG2fFg5h_JEOxbVvt_78VFYh4,2959
|
24
24
|
csc_cia_stne/utilitarios/functions/func_recriar_pastas.py,sha256=4whZpB3aJQaCPJ3osMAQpKrzEhqYtJbljGWlx_OvKIM,826
|
25
25
|
csc_cia_stne/utilitarios/functions/func_settings.py,sha256=XwlfqdcfocXQ8kTsDKZ6GsAtpzr0_u44AOTIMtdem7U,2059
|
26
26
|
csc_cia_stne/utilitarios/functions/func_titulo.py,sha256=bH4tYxovTARF-g2kWUK_GIzzXt8egbVdp6mWD6fc_3I,5345
|
@@ -32,8 +32,12 @@ csc_cia_stne/utilitarios/validations/ftp.py,sha256=LNYyS2c8eou3ML23bBtn87xJFIKSr
|
|
32
32
|
csc_cia_stne/utilitarios/validations/gcp_bucket.py,sha256=vqj70jBAkazydUCPXIdE3zzgoz8Te2cCJNX_rICX1aM,6096
|
33
33
|
csc_cia_stne/utilitarios/validations/waccess.py,sha256=8yfOrmIPUSLzbCt6P0F6vj3FkSgU_RgrJpJlRhlLyV0,7352
|
34
34
|
csc_cia_stne/utilitarios/validations/web_validator.py,sha256=HYKYSpDv1RvRjZIuwTPt-AbEz-9392MxM_O329iYuSA,5722
|
35
|
-
csc_cia_stne
|
36
|
-
csc_cia_stne
|
37
|
-
csc_cia_stne
|
38
|
-
csc_cia_stne
|
39
|
-
csc_cia_stne-0.1.
|
35
|
+
csc_cia_stne/utilitarios/web_screen/__init__.py,sha256=5QcOPXKd95SvP2DoZiHS0gaU68GlyFD9pQ9kae_9D1Q,100
|
36
|
+
csc_cia_stne/utilitarios/web_screen/web_screen_abstract.py,sha256=PjL8Vgfj_JdKidia7RFyCkro3avYLQu4RZRos41sh3w,3241
|
37
|
+
csc_cia_stne/utilitarios/web_screen/web_screen_botcity.py,sha256=3AzcP86nwBmitdXQNscv8fvg6dUogg2cAbG5KbuyqMM,12196
|
38
|
+
csc_cia_stne/utilitarios/web_screen/web_screen_selenium.py,sha256=xtnU3gLHPhptrz7D4TzAXQNC_7xl01GxVFfE7VkMV_U,15104
|
39
|
+
csc_cia_stne-0.1.2.dist-info/licenses/LICENCE,sha256=LPGMtgKki2C3KEZP7hDhA1HBrlq5JCHkIeStUCLEMx4,1073
|
40
|
+
csc_cia_stne-0.1.2.dist-info/METADATA,sha256=Zq5e13HVgOUHN0ysAvytwUCRX44jEbr7ZtfvCfYq4s8,1418
|
41
|
+
csc_cia_stne-0.1.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
42
|
+
csc_cia_stne-0.1.2.dist-info/top_level.txt,sha256=ldo7GVv3tQx5KJvwBzdZzzQmjPys2NDVVn1rv0BOF2Q,13
|
43
|
+
csc_cia_stne-0.1.2.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|