Created
February 6, 2021 07:52
-
-
Save matdashell/2edac1a483bbf7672a888d9f096812bf to your computer and use it in GitHub Desktop.
Multi threads selenium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Default ignored files | |
/shelf/ | |
/workspace.xml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<component name="InspectionProjectProfileManager"> | |
<profile version="1.0"> | |
<option name="myName" value="Project Default" /> | |
<inspection_tool class="Deprecation" enabled="false" level="WARNING" enabled_by_default="false" /> | |
<inspection_tool class="InstantiationOfUtilityClass" enabled="false" level="WARNING" enabled_by_default="false" /> | |
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false"> | |
<option name="processCode" value="true" /> | |
<option name="processLiterals" value="true" /> | |
<option name="processComments" value="true" /> | |
</inspection_tool> | |
</profile> | |
</component> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="ProjectRootManager" version="2" languageLevel="JDK_15" project-jdk-name="15" project-jdk-type="JavaSDK"> | |
<output url="file://$PROJECT_DIR$/out" /> | |
</component> | |
</project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="ProjectModuleManager"> | |
<modules> | |
<module fileurl="file://$PROJECT_DIR$/MultiThreads.iml" filepath="$PROJECT_DIR$/MultiThreads.iml" /> | |
</modules> | |
</component> | |
</project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="ChangeListManager"> | |
<list default="true" id="92d9ed99-601d-4918-a46e-e2b0a6a03c73" name="Default Changelist" comment="" /> | |
<option name="SHOW_DIALOG" value="false" /> | |
<option name="HIGHLIGHT_CONFLICTS" value="true" /> | |
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> | |
<option name="LAST_RESOLUTION" value="IGNORE" /> | |
</component> | |
<component name="GitToolBoxStore"> | |
<option name="projectConfigVersion" value="2" /> | |
</component> | |
<component name="ProjectId" id="1o6ATwoGOU0TknhAHyZOujO6i8s" /> | |
<component name="ProjectViewState"> | |
<option name="hideEmptyMiddlePackages" value="true" /> | |
<option name="showLibraryContents" value="true" /> | |
<option name="showMembers" value="true" /> | |
<option name="showVisibilityIcons" value="true" /> | |
</component> | |
<component name="PropertiesComponent"> | |
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" /> | |
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" /> | |
<property name="last_opened_file_path" value="$PROJECT_DIR$/../../DriversJava/Selenium/client-combined-3.141.59.jar" /> | |
<property name="project.structure.last.edited" value="Modules" /> | |
<property name="project.structure.proportion" value="0.0" /> | |
<property name="project.structure.side.proportion" value="0.2" /> | |
</component> | |
<component name="RecentsManager"> | |
<key name="CopyFile.RECENT_KEYS"> | |
<recent name="C:\Users\birocronix\Documents\Java\ClassesProject\MultiThreads\src" /> | |
</key> | |
</component> | |
<component name="RunManager"> | |
<configuration name="Main" type="Application" factoryName="Application"> | |
<option name="MAIN_CLASS_NAME" value="Bots" /> | |
<module name="MultiThreads" /> | |
<method v="2"> | |
<option name="Make" enabled="true" /> | |
</method> | |
</configuration> | |
</component> | |
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" /> | |
<component name="TaskManager"> | |
<task active="true" id="Default" summary="Default task"> | |
<changelist id="92d9ed99-601d-4918-a46e-e2b0a6a03c73" name="Default Changelist" comment="" /> | |
<created>1612596677405</created> | |
<option name="number" value="Default" /> | |
<option name="presentableId" value="Default" /> | |
<updated>1612596677405</updated> | |
</task> | |
<servers /> | |
</component> | |
</project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<module type="JAVA_MODULE" version="4"> | |
<component name="NewModuleRootManager" inherit-compiler-output="true"> | |
<exclude-output /> | |
<content url="file://$MODULE_DIR$"> | |
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> | |
</content> | |
<orderEntry type="inheritedJdk" /> | |
<orderEntry type="sourceFolder" forTests="false" /> | |
<orderEntry type="module-library" exported=""> | |
<library> | |
<CLASSES> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/libs/byte-buddy-1.8.15.jar!/" /> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/libs/commons-exec-1.3.jar!/" /> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/libs/guava-25.0-jre.jar!/" /> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/libs/okhttp-3.11.0.jar!/" /> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/libs/okio-1.14.0.jar!/" /> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/client-combined-3.141.59.jar!/" /> | |
</CLASSES> | |
<JAVADOC /> | |
<SOURCES> | |
<root url="jar://$MODULE_DIR$/../../DriversJava/Selenium/client-combined-3.141.59-sources.jar!/" /> | |
</SOURCES> | |
</library> | |
</orderEntry> | |
</component> | |
</module> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.util.function.Function; | |
public class Bots { | |
public static Function<Find, Exception> algoritimoExecutavel = null; | |
public static boolean paginaVisivel = true; | |
public static int numeroDeExecucoes = 5; | |
public static int numeroDeThreads = 2; | |
public static int tempoDeEsperaDriver = 10; | |
//localProject-> | |
public static void main(String[] args) { | |
algoritimoExecutavel = find -> { | |
try { find.init(paginaVisivel); } catch (AWTException e) { e.printStackTrace(); } | |
/*Area de Código*/ | |
/*Area de Código*/ | |
return null; | |
}; | |
new OrdenarThreads(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.openqa.selenium.By; | |
import org.openqa.selenium.Keys; | |
import org.openqa.selenium.WebDriver; | |
import org.openqa.selenium.WebElement; | |
import org.openqa.selenium.chrome.ChromeDriver; | |
import org.openqa.selenium.chrome.ChromeOptions; | |
import java.awt.*; | |
import java.util.*; | |
import java.util.List; | |
import java.util.concurrent.TimeUnit; | |
import static java.lang.Thread.sleep; | |
@SuppressWarnings("ALL") | |
public class Find { | |
public WebDriver driver = null; | |
Robot r = null; | |
int meuNumero; | |
int numeroThread; | |
static int numeroDeBots = 0; | |
static WebElement html = null; | |
//Configuração do selenium usndo o navegador Chrome | |
public Find() { | |
meuNumero = Find.numeroDeBots; | |
Find.numeroDeBots++; | |
} | |
//configuração para iniciar o driver | |
public void init(boolean headless) throws AWTException { | |
System.setProperty("webdriver.chrome.driver", "C:\\RecursosPng\\chromedriver.exe"); | |
ChromeOptions options = new ChromeOptions(); | |
if(!headless) { options.addArguments("--headless"); } | |
driver = new ChromeDriver(options); | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver, TimeUnit.SECONDS); | |
} | |
//retorno um unico elemento com base na busca | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
public WebElement one(String busca){ | |
return auxReturnWebDriver(driver, busca).get(0); | |
} | |
//retorna um unico elemento com base na busca no elemento no input | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
//sobrecaga | |
public static WebElement one(WebElement webElement ,String busca){ | |
return auxReturnWebElement(webElement, busca).get(0); | |
} | |
//retorna um unico elemento com base na busca no driver no input | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
//sobrecaga | |
public WebElement one(WebDriver webDriver ,String busca){ | |
return auxReturnWebDriver(webDriver, busca).get(0); | |
} | |
//retorna uma lista de elemento com base na busca | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
public List<WebElement> more(String busca){ | |
return auxReturnWebDriver(driver, busca); | |
} | |
//retorna uma lista de elementos com base na busca do elemento no input | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
//sobrecaga | |
public static List<WebElement> more(WebElement webElement ,String busca){ | |
return auxReturnWebElement(webElement, busca); | |
} | |
//retorna uma lista de elementos com base na busca no driver no input | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
//sobrecaga | |
public List<WebElement> more(WebDriver webDriver ,String busca){ | |
return auxReturnWebDriver(webDriver, busca); | |
} | |
//retorna o primeiro elemento com base na busca da lista no input | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
//sobrecaga | |
public static WebElement one(List<WebElement> listaWE ,String busca){ | |
for(WebElement dados : listaWE){ | |
return auxReturnWebElement(dados, busca).get(0); | |
} | |
return null; | |
} | |
//retorna uma lista de elementos com base na busca de todos os elemento da lista no input | |
//em caso de erro retorna null e adiciona o erro ao log com o código | |
//sobrecaga | |
public static List<WebElement> more(List<WebElement> listaWE ,String busca){ | |
List<WebElement> retorno = new ArrayList<>(); | |
List<WebElement> temp = new ArrayList<>(); | |
for(WebElement dados : listaWE){ | |
try { | |
temp = (auxReturnWebElement(dados, busca)); | |
}catch (Exception e){ | |
continue; | |
} | |
for(WebElement elementos : temp) { | |
retorno.add(elementos); | |
} | |
} | |
return retorno; | |
} | |
//tem função de aguardar enquanto o elemento procurado está ativo na tela | |
public void waitWhileEnable(String busca){ | |
driver.manage().timeouts().implicitlyWait(200,TimeUnit.MILLISECONDS); | |
boolean esperar = true; | |
try{ | |
while(esperar) { | |
time(500); | |
esperar = false; | |
if(one(busca) != null){ | |
esperar = true; | |
} | |
} | |
}catch (Exception ignored){ } | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
} | |
////tem função de aguardar enquanto o elemento procurado está ativo na tela | |
//sobrecarga | |
public void waitWhileEnable(WebElement webElement ,String busca){ | |
driver.manage().timeouts().implicitlyWait(200,TimeUnit.MILLISECONDS); | |
boolean esperar = true; | |
try{ | |
while(esperar) { | |
time(500); | |
esperar = false; | |
if(one(webElement ,busca) != null){ | |
esperar = true; | |
} | |
} | |
}catch (Exception ignored){ } | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
} | |
//tem função de aguardar enquanto o elemento procurado não está ativo na tela | |
public void waitWhileDisable(String busca){ | |
driver.manage().timeouts().implicitlyWait(200,TimeUnit.MILLISECONDS); | |
boolean esperar = true; | |
try{ | |
while(esperar) { | |
time(500); | |
esperar = false; | |
if(one(busca) == null){ | |
esperar = true; | |
} | |
} | |
}catch (Exception ignored){ } | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
} | |
//tem função de aguardar enquanto o elemento procurado não está ativo na tela | |
//sobrecarga | |
public void waitWhileDisable(WebElement webElement ,String busca){ | |
driver.manage().timeouts().implicitlyWait(200,TimeUnit.MILLISECONDS); | |
boolean esperar = true; | |
try{ | |
while(esperar) { | |
time(500); | |
esperar = false; | |
if(one(webElement ,busca) == null){ | |
esperar = true; | |
} | |
} | |
}catch (Exception ignored){ } | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
} | |
//retorna um boolean com base da atividade do elemento procurado | |
public boolean visible(String busca){ | |
driver.manage().timeouts().implicitlyWait(200,TimeUnit.MILLISECONDS); | |
time(1000); | |
if(one(busca) == null){ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return false; | |
} | |
else{ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return true; | |
} | |
} | |
//retorna um boolean com base da atividade do elemento procurado | |
public boolean visible(String busca, int tempoMLS){ | |
driver.manage().timeouts().implicitlyWait(tempoMLS,TimeUnit.MILLISECONDS); | |
if(one(busca) == null){ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return false; | |
} | |
else{ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return true; | |
} | |
} | |
//retorna um boolean com base da atividade do elemento procurado | |
public boolean visible(WebElement webElement ,String busca){ | |
driver.manage().timeouts().implicitlyWait(200,TimeUnit.MILLISECONDS); | |
time(1000); | |
if(one(webElement ,busca) == null){ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return false; | |
} | |
else{ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return true; | |
} | |
} | |
//retorna um boolean com base da atividade do elemento procurado | |
public boolean visible(WebElement webElement ,String busca, int tempoMLS){ | |
driver.manage().timeouts().implicitlyWait(tempoMLS,TimeUnit.MILLISECONDS); | |
if(one(webElement ,busca) == null){ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return false; | |
} | |
else{ | |
driver.manage().timeouts().implicitlyWait(Bots.tempoDeEsperaDriver,TimeUnit.SECONDS); | |
return true; | |
} | |
} | |
//navega até uma página https | |
public void page(String url){ | |
driver.get(url); | |
} | |
//retorna o driver do navegador | |
public WebDriver driver(){ | |
return driver; | |
} | |
//encerrar a execução e mostrar os erros de execução | |
public synchronized void exit(){ | |
driver.quit(); | |
} | |
//tempo | |
public void time(long milissegundo){ | |
try{sleep(milissegundo);}catch (Exception ignored){} | |
} | |
//recarregar a pagina | |
public void reload(){ | |
time(1000); | |
one("css html").sendKeys(Keys.F5); | |
time((long) Bots.tempoDeEsperaDriver/2); | |
} | |
//obter o numero do bot (em caso de uso) | |
public int getNumero(){ | |
return meuNumero; | |
} | |
//filtro de pesquisa de WebElements | |
public static List<WebElement> auxReturnWebElement(WebElement webElement, String busca){ | |
if (busca.startsWith("x")) { | |
return webElement.findElements(By.xpath(busca.substring(2))); | |
} else if (busca.startsWith("i")) { | |
return webElement.findElements(By.id(busca.substring(2))); | |
} else if (busca.startsWith("n")) { | |
return webElement.findElements(By.name(busca.substring(2))); | |
} else if (busca.startsWith("css")) { | |
return webElement.findElements(By.cssSelector(busca.substring(4))); | |
} else if (busca.startsWith("c")) { | |
return webElement.findElements(By.className(busca.substring(2))); | |
} else if (busca.startsWith("t")) { | |
return webElement.findElements(By.linkText(busca.substring(2))); | |
} else if (busca.startsWith("p")) { | |
return webElement.findElements(By.partialLinkText(busca.substring(2))); | |
} else if (busca.startsWith("tn")) { | |
return webElement.findElements(By.tagName(busca.substring(3))); | |
} else{ | |
System.out.println("erro ao filtrar elemento ["+busca+"]"); | |
System.exit(0); | |
} | |
return null; | |
} | |
//filtro de pesquisa de WebElements usando o WebDriver | |
public List<WebElement> auxReturnWebDriver(WebDriver webDriver, String busca) { | |
if (busca.startsWith("x")) { | |
return webDriver.findElements(By.xpath(busca.substring(2))); | |
} else if (busca.startsWith("i")) { | |
return webDriver.findElements(By.id(busca.substring(2))); | |
} else if (busca.startsWith("n")) { | |
return webDriver.findElements(By.name(busca.substring(2))); | |
} else if (busca.startsWith("css")) { | |
return webDriver.findElements(By.cssSelector(busca.substring(4))); | |
} else if (busca.startsWith("c")) { | |
return webDriver.findElements(By.className(busca.substring(2))); | |
} else if (busca.startsWith("t")) { | |
return webDriver.findElements(By.linkText(busca.substring(2))); | |
} else if (busca.startsWith("p")) { | |
return webDriver.findElements(By.partialLinkText(busca.substring(2))); | |
} else if (busca.startsWith("tn")) { | |
return webDriver.findElements(By.tagName(busca.substring(3))); | |
} else { | |
System.out.println("erro ao filtrar elemento [" + busca + "]"); | |
System.exit(0); | |
} | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.lang.Thread.sleep; | |
@SuppressWarnings("ALL") | |
public class MyThread { | |
static int quantidadeDeNucleos = 0; | |
static int quantidadeDeExecucoesNucleo = 0; | |
int meuNumero; | |
Find f = null; | |
Nucleo n = new Nucleo(); | |
boolean iniciado = false; | |
boolean processar = false; | |
public MyThread(){ | |
this.meuNumero = quantidadeDeNucleos; | |
quantidadeDeNucleos++; | |
} | |
public class Nucleo extends java.lang.Thread{ | |
public void run(){ | |
iniciado = true; | |
while(true){ | |
try{sleep(1000);}catch (Exception ignored){} | |
if(processar){ | |
/*funções do núcleo*/ | |
Bots.algoritimoExecutavel.apply(f); | |
alterarVariaveis(); | |
processar = false; | |
/*funções do núcleo*/ | |
} | |
} | |
} | |
} | |
public synchronized void setNucleo(){ | |
this.f = null; | |
this.f = new Find(); | |
this.f.numeroThread = meuNumero; | |
} | |
public synchronized void ligarNucleo(){ | |
setNucleo(); | |
if(this.iniciado){ | |
this.processar = true; | |
}else{ | |
this.processar = true; | |
this.n.start(); | |
} | |
} | |
public synchronized void encerrarNucleo(){ | |
this.n.stop(); | |
} | |
public synchronized static void alterarVariaveis(){ | |
try{sleep(1);}catch (Exception e){} | |
quantidadeDeExecucoesNucleo++; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import static java.lang.Thread.sleep; | |
@SuppressWarnings("ALL") | |
public class OrdenarThreads{ | |
static List<MyThread> myThreadList = new ArrayList<>(); | |
static int controleDeExecucoes = 0; | |
public OrdenarThreads(){ | |
for (int i = 0; i < Bots.numeroDeThreads; i++){ | |
myThreadList.add(new MyThread()); | |
} | |
executarThreads(); | |
encerrarThreads(); | |
} | |
public static void executarThreads(){ | |
while(MyThread.quantidadeDeExecucoesNucleo < Bots.numeroDeExecucoes){ | |
try{sleep(1000);}catch (Exception ignored){} | |
myThreadList | |
.forEach(myThread -> { | |
if (!myThread.processar && controleDeExecucoes < Bots.numeroDeExecucoes) { | |
myThread.ligarNucleo(); | |
controleDeExecucoes++; | |
} | |
} | |
); | |
} | |
} | |
public static void encerrarThreads(){ | |
myThreadList.forEach(MyThread::encerrarNucleo); | |
myThreadList = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment