-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
214 lines (186 loc) · 10.4 KB
/
Program.cs
File metadata and controls
214 lines (186 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace WebAutomation
{
class Program
{
static void Main(string[] args)
{
// Configurar o driver do Chrome
var options = new ChromeOptions();
options.AddArgument("--start-maximized"); // Maximizar a janela
options.AddArgument("--disable-blink-features=AutomationControlled"); // Evitar detecção de automação
using var driver = new ChromeDriver(options);
try
{
Console.WriteLine("Iniciando automação...");
// Navegar para a URL
string url = "http://localhost:3000/simulacao/resultado/714";
driver.Navigate().GoToUrl(url);
Console.WriteLine($"Navegando para: {url}");
// Aguardar a página carregar
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
Console.WriteLine("Página carregada com sucesso!");
// Aguardar que o elemento "Carregando..." desapareça
Console.WriteLine("Aguardando carregamento completo...");
try
{
// Aguardar até que não haja mais elementos com "Carregando..."
wait.Until(d => !d.FindElements(By.XPath("//*[contains(text(), 'Carregando')]")).Any());
Console.WriteLine("Carregamento concluído!");
}
catch (TimeoutException)
{
Console.WriteLine("Timeout aguardando carregamento, continuando...");
}
// Aguardar um pouco para garantir que todos os elementos estejam carregados
Thread.Sleep(3000);
// Procurar e clicar no elemento "Emergência"
Console.WriteLine("Procurando pelo elemento 'Emergência'...");
// Debug: imprimir informações da página
Console.WriteLine($"Título da página: {driver.Title}");
Console.WriteLine($"URL atual: {driver.Url}");
// Tentar diferentes seletores para encontrar o elemento "Emergência"
IWebElement? emergenciaElement = null;
// Primeiro, vamos listar todos os elementos que contêm texto para debug
Console.WriteLine("Debug: Procurando todos os elementos com texto...");
try
{
var allTextElements = driver.FindElements(By.XPath("//*[text()]"));
Console.WriteLine($"Encontrados {allTextElements.Count} elementos com texto");
foreach (var element in allTextElements.Take(20)) // Limitar a 20 elementos
{
try
{
var text = element.Text?.Trim();
if (!string.IsNullOrEmpty(text))
{
Console.WriteLine($"- {element.TagName}: '{text}'");
if (text.Contains("Emergência", StringComparison.OrdinalIgnoreCase))
{
emergenciaElement = element;
Console.WriteLine("*** Elemento 'Emergência' encontrado! ***");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao acessar elemento: {ex.Message}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao buscar elementos: {ex.Message}");
}
// Se não encontrou ainda, tentar estratégias específicas
if (emergenciaElement == null)
{
Console.WriteLine("Tentando estratégias específicas de busca...");
try
{
// Estratégia 1: Busca case-insensitive
emergenciaElement = driver.FindElement(By.XPath("//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'emergência')]"));
Console.WriteLine("Encontrado com busca case-insensitive!");
}
catch (NoSuchElementException)
{
try
{
// Estratégia 2: Busca por elementos clicáveis
emergenciaElement = driver.FindElement(By.XPath("//button[contains(text(), 'Emergência')] | //a[contains(text(), 'Emergência')] | //div[contains(text(), 'Emergência') and (@onclick or @role='button')]"));
Console.WriteLine("Encontrado elemento clicável!");
}
catch (NoSuchElementException)
{
try
{
// Estratégia 3: Busca por atributos
emergenciaElement = driver.FindElement(By.XPath("//*[@title='Emergência' or @aria-label='Emergência']"));
Console.WriteLine("Encontrado por atributos!");
}
catch (NoSuchElementException)
{
Console.WriteLine("Elemento 'Emergência' não encontrado com nenhuma estratégia.");
// Debug: salvar screenshot e HTML
try
{
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile("/Users/danilo/Desktop/end_to_end/debug_screenshot.png");
Console.WriteLine("Screenshot salvo em: debug_screenshot.png");
File.WriteAllText("/Users/danilo/Desktop/end_to_end/debug_page_source.html", driver.PageSource);
Console.WriteLine("HTML da página salvo em: debug_page_source.html");
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao salvar debug: {ex.Message}");
}
}
}
}
}
if (emergenciaElement != null)
{
Console.WriteLine("Elemento 'Emergência' encontrado! Clicando...");
// Scroll para o elemento se necessário
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", emergenciaElement);
Thread.Sleep(500);
// Clicar no elemento
emergenciaElement.Click();
Console.WriteLine("Clique realizado com sucesso!");
// Aguardar 5 segundos
Console.WriteLine("Aguardando 5 segundos...");
Thread.Sleep(5000);
// Procurar e clicar no botão para fechar o risco
Console.WriteLine("Procurando botão para fechar o risco...");
try
{
// Tentar encontrar botão de fechar (X) ou toggle
var closeButton = wait.Until(d =>
d.FindElement(By.XPath("//button[contains(@class, 'close')] | //button[contains(@aria-label, 'close')] | //*[contains(@class, 'toggle')] | //button[contains(text(), 'Fechar')] | //*[@role='button' and contains(@class, 'active')]")));
closeButton.Click();
Console.WriteLine("Risco fechado com sucesso!");
}
catch (NoSuchElementException)
{
Console.WriteLine("Botão de fechar não encontrado. Tentando encontrar toggle...");
// Tentar encontrar o toggle verde que estava ativo
try
{
var toggle = wait.Until(d =>
d.FindElement(By.XPath("//input[@type='checkbox' and @checked] | //*[contains(@class, 'toggle') and contains(@class, 'active')] | //*[@role='switch' and @aria-checked='true']")));
toggle.Click();
Console.WriteLine("Toggle clicado para fechar o risco!");
}
catch (NoSuchElementException)
{
Console.WriteLine("Não foi possível encontrar o botão para fechar o risco.");
}
}
}
else
{
Console.WriteLine("ERRO: Elemento 'Emergência' não foi encontrado!");
// Debug: imprimir o HTML da página
Console.WriteLine("HTML da página:");
Console.WriteLine(driver.PageSource);
}
Console.WriteLine("Automação concluída!");
}
catch (Exception ex)
{
Console.WriteLine($"Erro durante a automação: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
}
finally
{
// Aguardar um pouco antes de fechar
Thread.Sleep(2000);
driver.Quit();
Console.WriteLine("Driver fechado.");
}
}
}
}