Estou estudando o selenium para enviar mensagens automática para vários contatos usando um loop. O porgrama envia para 2 ou 3 contatos, mas depois para de enviar e não finaliza o programa. Gostaria de uma ajuda para descobrir o que está acontecendo e como resolver.
GoogleChrome.java
package com.selenium.whatsapp.service;
import java.sql.Time;
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties.Timeouts;
import dev.failsafe.Timeout;
//ESSA CLASSE SERÁ A RESPONSÁVEL POR MANIPULAR O NAVEGADOR E INICIAR A AUTOMAÇÃO DO WHATSAPP.
public class GoogleChrome {
private boolean status;
// ESTÁ SENDO INFORMADO QUAL DRIVER SERÁ USADO.
// E A LOCALIZAÇÃO DO CHROME DRIVER.
public ChromeDriver iniciarAplicativo() {
System.setProperty("webdriver.chrome.driver", "chromedriver");
ChromeOptions options = new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.NONE);
return new ChromeDriver(options);
}
// ESTE MÉTODO DEFINE O TEMPO DE ESPERA.
// É USADO QUANDO UM ELEMENTO HTML AINDA NÃO FOI CARREGADO NA PÁGINA.
public WebDriverWait esperar(ChromeDriver chromeDriver) {
return new WebDriverWait(chromeDriver, Duration.ofDays(1));
}
// ESTE MÉTODO VAI ACESSAR O WHATSAPP WEB.
public void acessarWhatsapp(ChromeDriver chromeDriver, String[] contatos, String texto) {
chromeDriver.get("https://web.whatsapp.com/send/?phone=" + contatos[1] + "&text=" + texto);
}
// NO MOMENTO QUE O WHATSAPP ESTÁ INICIANDO A CONVERSA, É VERIFICADO SE EXISTE
// UM ALERTA OU NÃO.
public void verificaAlertaPresente(ChromeDriver chromeDriver) {
try {
Alert alert = ExpectedConditions.alertIsPresent().apply(chromeDriver);
alert.accept();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (UnhandledAlertException e) {
System.out.println(e.getMessage());
}
}
// ESTE MÉTODO VAI AGUARDAR UM ELEMENTO ESPECÍFICO SER CARREGADO NA PÁGINA DE
// CONVERSA E,
// EM SEGUIDA, ENVIAR A MENSAGEM PROGRAMADA E ESPERAR 5 SEGUNDOS.
public void mensagemTexto(WebDriverWait wait, ChromeDriver chromeDriver) throws InterruptedException {
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[@class=\'selectable-text copyable-text\']")));
// System.out.println(element.getText());
// this.pausarExecucao(3000);
element.sendKeys(Keys.ENTER);
this.pausarExecucao(3000);
}
public void mensagemImagem(String mensagemImagem, ChromeDriver chromeDriver, WebDriverWait wait)
throws InterruptedException {
WebElement anexar = chromeDriver.findElement(By.xpath("//div[@title='Anexar']"));
anexar.click();
this.pausarExecucao(3000);
WebElement upload = chromeDriver.findElement(By.tagName("input"));
upload.sendKeys(mensagemImagem);
this.pausarExecucao(3000);
WebElement botãoEnviar = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("_33pCO")));
botãoEnviar.click();
this.pausarExecucao(5000);
}
public boolean alertaNumeroComWhatsapp(WebDriverWait wait, ChromeDriver chromeDriver, String[] vetor, String texto)
throws InterruptedException {
this.status = true;
WebElement botao = null;
WebElement popup = null;
try {
popup = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("_3J6wB")));
this.popup(popup, botao);
} catch (StaleElementReferenceException e) {
this.popup(popup, botao);
}
return status;
}
public void pausarExecucao(long milisegundos) throws InterruptedException {
Thread.sleep(milisegundos);
}
public void popup(WebElement popup, WebElement botao) throws InterruptedException {
//System.out.println(popup.getText());
//if (popup.isDisplayed()) {
//this.pausarExecucao(2000);
if (popup.findElement(By.className("_2Nr6U")).getText()
.equals("O número de telefone compartilhado através de url é inválido.")) {
System.out.println("funcionando...");
System.out.println(popup.findElement(By.xpath("//div[@class=\'_2Nr6U\']")).getText());
botao = popup.findElement(By.xpath("//div[@class=\'_20C5O _2Zdgs\']"));
botao.click();
this.status = false;
}
//}
}
}
package com.selenium.whatsapp.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Whatsapp {
//ATRIBUTOS E OBJETOS
private GoogleChrome googleChrome;
private ChromeDriver chromeDriver;
private WebDriverWait wait;
private BufferedReader reader;
public void enviarMensagensEmMassa(String texto, String caminhoImagem) throws InterruptedException {
String linha;
boolean status;
try {
reader = new BufferedReader(new FileReader(new File("planilha.csv")));
googleChrome = new GoogleChrome();
chromeDriver = googleChrome.iniciarAplicativo();
wait = googleChrome.esperar(chromeDriver);
while((linha = reader.readLine()) != null) {
String[] vetor = linha.split(";");
googleChrome.acessarWhatsapp(chromeDriver, vetor, texto);
status = googleChrome.alertaNumeroComWhatsapp(wait, chromeDriver, vetor, texto);
System.out.println(status);
if(status == true) {
googleChrome.mensagemTexto(wait, chromeDriver);
googleChrome.mensagemImagem(caminhoImagem, chromeDriver, wait);
}
//googleChrome.pausarExecucao(3000);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage());
}catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}
Classe Principal
package com.example.erp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.fasterxml.jackson.datatype.jsr310.util.DurationUnitConverter;
import com.selenium.whatsapp.service.Whatsapp;
import ch.qos.logback.core.joran.action.Action;
@SpringBootApplication
public class SeleniumApplication {
public static void main(String[] args) throws IOException, InterruptedException{
SpringApplication.run(SeleniumApplication.class, args);
File caminhoArquivo = new File("cobrança.docx");
String caminhoImagem = "/home/carlos/Documents/workspace-spring-tool-suite-4-4.14.1.RELEASE/selenium/aviso.jpeg";
FileInputStream arquivo = new FileInputStream(caminhoArquivo);
XWPFDocument documento = new XWPFDocument(arquivo);
XWPFWordExtractor extractor = new XWPFWordExtractor(documento);
String texto = null;
Whatsapp whatsapp = new Whatsapp();
/*ChromeDriver chromeDriver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofDays(1));
boolean status = true;*/
texto = URLEncoder.encode(extractor.getText(), StandardCharsets.UTF_8);
whatsapp.enviarMensagensEmMassa(texto, caminhoImagem);
System.out.println("Programa executado com sucesso!!!");
}
}