Durante a edição de scripts no EveryStep Scripting Tool Desktop, você pode adicionar um código C# personalizado. Consulte EveryStep Scripting Tool Object Model: classes, methods, properties, etc . para encontrar mais informações sobre a personalização de script EveryStep.

Os scripts que foram editados com código C# personalizado exigem uma aprovação de nossa equipe de suporte técnico antes de serem salvos. Toda vez que você adicionar um código C# personalizado ou editar um script que contenha código C# personalizado, o script será enviado para aprovação automaticamente. Observe que pode levar algum tempo para que nossa equipe revise e aprove o script para uso.

Aqui estão alguns exemplos de adição de C# em um script para usar instruções condicionais e variáveis definidas aleatoriamente:

Exemplos de instrução condicional

Abortando a execução do script em um erro de validação de conteúdo

Step (1, "test - https://www.test.com");
tab0 = Tabs.NewTab ();
tab0.GoTo ("https://www.test.com");
if ( !tab0.Text.Contains("<KEYWORD>"))
{
return;
}
Por exemplo, para abortar o script se a palavra-chave “Login” não for encontrada, adicione:
if (!tab0.Text.Contains("Login"))

Fechando pop-ups condicionais se aparecerem

As condições de repetição do script podem variar dependendo das regiões geográficas, tempo, etc. Assim, alguns conteúdos, como pop-ups, podem ser exibidos com base nas condições enquanto reproduzimos o script. Para especificar como você deseja gerenciar o conteúdo condicional no site de destino, adicione a instrução if ao script EveryStep.

Por exemplo, para fechar um pop-up se ele for exibido na página durante uma repetição de script e navegar para uma nova página

  1. Grave o script com o pop-up exibido na página.
  2. Como alternativa: se você tiver o Xpath para localizar o botão “Fechar” na página de destino, poderá gravar o script sem o pop-up.
  3. Adicione a instrução if na etapa em que o pop-up deve aparecer. Use o botão “Fechar” Xpath para especificar a condição.

Observe que usamos o método WaitForElement na expressão de teste “if” para aguardar que o pop-up seja carregado:

tab0.WaitForElement (TimeSpan timeout, string xpath)
// script_version=3.0; everystep_version=0; date=4/8/2022; Chrome=91.0.4472.77
NetworkFilter.Deny ("https://www.adidas.com/api/chk/customer/baskets?sitePath=us");
Tabs.SetSize (1820, 513);
DMBrowser tab0 = null;
Step (1, "adidas Official Website | adidas US - https://www.adidas.com/us/kids");
tab0 = Tabs.NewTab ();
tab0.GoTo ("https://www.adidas.com/");
tab0.Link ("//A[normalize-space(text())=\"KIDS\"]", "//A[normalize-space()=\"3 STRIPE LIFE\"]/../preceding-sibling::DIV[2]//A[normalize-space()=\"KIDS\"]", "//A[normalize-space()=\"Give Back\"]/../preceding-sibling::DIV[3]//A[normalize-space()=\"KIDS\"]").Click ();
Step (2, "Kids Shoes and Clothing | adidas US - https://www.adidas.com/us/kids");
//Waits for pop-up window with the "Close" button to appear on the page for 5 seconds. 
if (tab0.WaitForElement("5sec".ToDuration (), "//*[@ID=\"modal-root\"]/DIV/DIV/BUTTON", "//BUTTON[@ARIA-LABEL=\"Close\"]"))
{
//If the "Close" button detected, clicks the button to close the pop-up. Otherwise, jumps to the next line.
 tab0.Button ("//*[@ID=\"modal-root\"]/DIV/DIV/BUTTON", "//BUTTON[@ARIA-LABEL=\"Close\"]").Click ();
}
tab0.Span ("//A[normalize-space(@TITLE)=\"SHOP NOW\"]//SPAN[normalize-space()=\"SHOP NOW\"]", "//A[normalize-space(@TITLE)=\"SHOP NOW\"]//SPAN[normalize-space(text())=\"SHOP NOW\"]", "(//SPAN[normalize-space(text())=\"SHOP NOW\"])[1]").Click ();
Step (3, "Kids - Ultraboost 22 | adidas US - https://www.adidas.com/us/kids-ultraboost_22");

Adicionar o item ao carrinho de compras ou à lista de espera se o item não estiver disponível

Se… outra instrução permite que seu script execute ações específicas, como cliques em botões, verificações de chekbox, navegação para outra URL, etc. com base na condição especificada. Por exemplo, você pode gravar uma transação “adicionar ao carrinho de compras” e desejar que o script adicione um item ao carrinho ou, se estiver esgotado, a uma lista de espera. Você pode fazer isso adicionando um se… outra declaração:

  1. Registre a transação do carrinho de compras.
  2. Para especificar a expressão de teste, selecione o elemento que indica que o item está em estoque, por exemplo, o botão “Comprar agora”.
  3. Especifique a instrução “if” depois de navegar para a página do item usando a tab0. Método WaitForElement (TimeSpan timeout, string xpath) com o botão “Buy Now” Xpath.
  4. Especifique a ação a ser executada se o item estiver disponível como a instrução “if”. Por exemplo, o clique em “Comprar agora”.
  5. Especifique a ação a ser executada se o item estiver fora de estoque (nenhum botão “Comprar agora” detectado) como a instrução “else”. Por exemplo, clique em “Adicionar à lista”.

Dicas

Para especificar ações de fluxo alternativas, registre as ações além do fluxo padrão dentro do mesmo script. Em seguida, use as linhas relacionadas na instrução “else”.

Confira o exemplo abaixo.

// script_version=3.0; everystep_version=0; date=4/8/2022; Chrome=91.0.4472.77
Tabs.SetSize (1820, 479);
DMBrowser tab0 = null;
Step (1, "International Shopping: Shop Computers that Ship Internationally - https://www.amazon.com/b?node=16225007011");
tab0 = Tabs.NewTab ();
tab0.GoTo ("https://www.amazon.com/b?node=16225007011");
tab0.Image ("//IMG[normalize-space(@ALT)=\"Seagate Portable 2TB External Hard Drive Portable HDD – USB 3.0 for PC, Mac, PlayStation, &amp; Xbox - 1-Year Rescue Service (...\"]", "/HTML/BODY/DIV[1]/DIV[2]/DIV[2]/DIV[1]/DIV[2]/DIV/DIV/DIV[2]/DIV[3]/DIV/DIV/SPAN/A/DIV/IMG").Click ();
Step (2, "Amazon.com: Seagate Portable 2TB External Hard Drive Portable HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox - 1-Year Rescue Service (STGX2000400) : Electronics - https://www.amazon.com/gp/product/handle-buy-box/ref=dp_start-bbf_1_glance");
tab0.Navigating ("https://www.amazon.com/gp/product/handle-buy-box/ref=dp_start-bbf_1_glance");
tab0.Para ("//P[normalize-space()=\"500 GB\"]", "//P[normalize-space(text())=\"500 GB\"]", "//LI[normalize-space(@TITLE)=\"Click to select 500 GB\"]/SPAN/DIV/SPAN/SPAN/SPAN/BUTTON/DIV/DIV[1]/P").Click ();

// Waits for the "Buy Now" button to be loaded on the page for 5 seconds. 
if (tab0.WaitForElement("5sec".ToDuration(), "//INPUT[@ID=\"buy-now-button\"]", "(//SPAN[normalize-space()=\"Buy Now\"])[last()]/..//INPUT[@TYPE=\"submit\"]", "(//SPAN[normalize-space()=\"Buy Now\"])[last()]/..//INPUT"))
{
If the "Buy Now" button detected, clicks the button. Otherwise, the "Buy Now" click is skipped from execution and the "Add to List" click is executed. 
tab0.Button ("//INPUT[@ID=\"buy-now-button\"]", "(//SPAN[normalize-space()=\"Buy Now\"])[last()]/..//INPUT[@TYPE=\"submit\"]", "(//SPAN[normalize-space()=\"Buy Now\"])[last()]/..//INPUT").Click ();
}
//if the "Buy Now" button not detected, finds and clicks "Add to List" button instead.
else
{
  tab0.Link ("//A[normalize-space()=\"Add to List\"]", "//A[normalize-space(text())=\"Add to List\"]", "//A[@NAME=\"submit.add-to-registry.wishlist.unrecognized\"]").Click ();
}
Step (3, "Amazon Sign-In - https://www.amazon.com/ap/signin?openid.return_to=https%3A%2F%2Fwww.amazon.com%2Fgp%2Faw%2Fd%2FB07X3XGG3F&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=usflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&");
tab0.Navigating ("https://www.amazon.com/ap/signin?openid.return_to=https%3A%2F%2Fwww.amazon.com%2Fgp%2Faw%2Fd%2FB07X3XGG3F&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=usflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&");

Randomização dos dados

Randomização de e-mails para processos de registro

Para usar e-mails gerados aleatoriamente no processo de registro, você pode declarar uma nova variável com o valor gerado aleatoriamente semelhante ao seguinte:

string mail = ("test" + Guid.NewGuid().ToString("N") + "@gmail.com");

Use a variável como o parâmetro do método TypeText para o campo de e-mail, conforme mostrado abaixo:

tab0.TextField ("//INPUT[@TYPE=\"text\"]", "//INPUT[@ID=\"Contact_Email_Addr\"]", "//INPUT).TypeText (mail.ToString ());
// script_version=3.0; everystep_version=4.0.8108.2121; date=4/8/2022; Chrome=91.0.4472.77
Tabs.SetSize (1768, 816);
DMBrowser tab0 = null;
//Declares the mail variable.
string mail = ("test+" + Guid.NewGuid().ToString("N") + "@gmail.com");
Step (1, "Dotcom-Monitor: Website Monitoring and Performance Testing - https://www.dotcom-monitor.com/");
tab0 = Tabs.NewTab ();
tab0.GoTo ("http://dotcom-monitor.com");
Tabs.SetSize (1768, 623);
tab0.Span ("(//SPAN[normalize-space(text())=\"Free Trial\"])[1]", "(//DIV[@ID=\"jivo-iframe-container\"]/preceding-sibling::DIV[3]//SPAN[normalize-space(text())=\"Free Trial\"])[1]", "(//IFRAME[normalize-space(@TITLE)=\"Jivochat\"]/../preceding-sibling::DIV[3]//SPAN[normalize-space(text())=\"Free Trial\"])[1]").Click ();
Step (2, "Free Trial Sign Up - https://userauth.dotcom-monitor.com/Account/FreeTrialSignUp");
tab0.Navigating ("https://userauth.dotcom-monitor.com/Account/FreeTrialSignUp");
tab0.TextField ("//INPUT[@TYPE=\"text\"]", "//INPUT[@ID=\"Contact_Email_Addr\"]", "//INPUT").Click ();
//Sets the email value to the randomly generated value of the mail variable.
tab0.TextField ("//INPUT[@TYPE=\"text\"]", "//INPUT[@ID=\"Contact_Email_Addr\"]", "//INPUT").TypeText (mail.ToString ());
tab0.Button ("//BUTTON[normalize-space()=\"Start Free Trial\"]", "//BUTTON[normalize-space(text())=\"Start Free Trial\"]", "//BUTTON[@TYPE=\"button\"]").Click ();

Entrando entre 18 e 12 anos.

// script_version=3.0; everystep_version=4.0.5953.25078; date=4/19/2016; IE=11.0.9600.17126
Tabs.ConfigureIEVersion (BrowserMode.IE11, DocumentMode.IE11Emulate);
Tabs.SetSize (1768, 651);
DMBrowser tab0 = null;
Step (1, "The input element - HTML5 tutorial - http://www.html-5-tutorial.com/input-element.php");
tab0 = Tabs.NewTab ();
tab0.GoTo ("http://www.html-5-tutorial.com/input-element.php");

// produces random number in range from 18 to 120
int r = (new Random(DateTime.Now.Second)).Next(18, 121);

tab0.TextField ("//INPUT[@TYPE=\"number\"]", "//INPUT[@NAME=\"age\"]", "//B[normalize-space()=\"Age:\"]/..//INPUT").TypeText (r.ToString());

Escolhendo aleatoriamente sexo masculino ou feminino

// script_version=3.0; everystep_version=4.0.5953.25078; date=4/19/2016; IE=11.0.9600.17126

Tabs.ConfigureIEVersion (BrowserMode.IE11, DocumentMode.IE11Emulate);
Tabs.SetSize (1768, 714);
DMBrowser tab0 = null;
Step (1, "visible - http://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_radio");
tab0 = Tabs.NewTab ();
tab0.GoTo ("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_radio");
for (int i = 0; i < 5; i++)

// produces random number in range from 0 to 2

int r = (new Random(DateTime.Now.Second)).Next(0, 3);
if (r == 0)
{
tab0.Frame ("//IFRAME[@ID=\"iframeResult\"]", "//IFRAME").RadioButton ("//INPUT[@VALUE=\"female\"]", "//INPUT[@VALUE=\"other\"]/preceding-sibling::INPUT[1]", "//INPUT[@VALUE=\"male\"]/following-sibling::INPUT[1]").Click ();
}
else if (r == 1)
{
tab0.Frame ("//IFRAME[@ID=\"iframeResult\"]", "//IFRAME").RadioButton ("//INPUT[@VALUE=\"other\"]", "//INPUT[@VALUE=\"female\"]/following-sibling::INPUT[1]", "//INPUT[@VALUE=\"male\"]/following-sibling::INPUT[2]").Click ();
}
else if (r == 2)
{
tab0.Frame ("//IFRAME[@ID=\"iframeResult\"]", "//IFRAME").RadioButton ("//INPUT[@VALUE=\"male\"]", "(//INPUT[@TYPE=\"radio\"])[1]", "(//INPUT[@NAME=\"gender\"])[1]").Click ();
}
Delay("3sec".ToDuration());
}

Escolhendo um item aleatório de um catálogo de produtos online

Para criar um script que seleciona repetidamente itens aleatórios de um catálogo online, use o exemplo fornecido abaixo. Observe que é recomendável gravar vários cliques no item primeiro para facilitar a edição da origem posteriormente.

// script_version=3.0; everystep_version=4.0.8108.2121; date=4/12/2022; Chrome=91.0.4472.77
Tabs.SetSize (1768, 714);
DMBrowser tab0 = null;
Step (1, "Amazon.com: Jewelry Made in Italy: Clothing, Shoes & Jewelry - https://www.amazon.com/b?node=19219863011&pf_rd_r=ZS16WVQN9RD996FPB6TH&pf_rd_p=0b9330ec-285a-4f51-9e1c-6765ca451c5f&pd_rd_r=3b9e3cf5-d247-4f50-8d15-a6683fa46846&pd_rd_w=uNsg8&pd_rd_wg=xFg13&ref_=pd_gw_unk");
tab0 = Tabs.NewTab ();
tab0.GoTo ("https://www.amazon.com/b?node=19219863011&pf_rd_r=ZS16WVQN9RD996FPB6TH&pf_rd_p=0b9330ec-285a-4f51-9e1c-6765ca451c5f&pd_rd_r=3b9e3cf5-d247-4f50-8d15-a6683fa46846&pd_rd_w=uNsg8&pd_rd_wg=xFg13&ref_=pd_gw_unk");

//Collects all images to count the total number of images in the body and saves them to the body's Attribute
tab0.RunScript("(function(){const imgCount=document.querySelectorAll(\".s-image\").length;document.body.setAttribute(\"data-imgCount\", imgCount);})()");
int count = 0;

//Gets the value of the Attribute 
string countString = tab0.Element("//BODY").GetAttributeValue("data-imgCount");

//If countString parsed successfully then clicks a random image on the page. Otherwise, raises an error. 
if (!int.TryParse(countString, out count)) {
  RaiseError(string.Format("Failed to get elements count: {0}", countString));
} else {
  var rnd = new Random();
  int i = rnd.Next(1, count);

//Clicks the picked image  
  tab0.Image (string.Format ("(//IMG[@CLASS=\"s-image\"])[{0}]", i)).Click ();

//Navigates to the item page
Step (2, string.Format ("Amazon.com: Selected Item {0}", i));

//Waits for the navigation to be finished. The Navigating (string url) argument can be set to a random URL since it is being scripted while the source script recording and not interfered with the script execution logic. However, the specified URL will be presented in the report data. Check report data for network requests to find an actual URL that was used in the related script run.
tab0.Navigating ("https://www.amazon.com/KEZEF-Creations-Sterling-Overlay-Necklace/dp/B008Y357US/ref=lp_19219863011_1_1");

//Navigates back to the main page and repeats the cycle. You can populate the following lines as many times as necessary within your script.
Step (3, "Amazon.com: Jewelry Made in Italy: Clothing, Shoes & Jewelry - https://www.amazon.com/b?node=19219863011&pf_rd_r=ZS16WVQN9RD996FPB6TH&pf_rd_p=0b9330ec-285a-4f51-9e1c-6765ca451c5f&pd_rd_r=3b9e3cf5-d247-4f50-8d15-a6683fa46846&pd_rd_w=uNsg8&pd_rd_wg=xFg13&ref_=pd_gw_unk");
tab0.Back ();
  i = rnd.Next(1, count);
  tab0.Image (string.Format ("(//IMG[@CLASS=\"s-image\"])[{0}]", i)).Click ();
Step (4, string.Format ("Amazon.com: Selected Item {0}", i));
tab0.Navigating ("https://www.amazon.com/Saint-MIchael-Archangel-Medal-Patron/dp/B01G3K6M5C/ref=lp_19219863011_1_3");
Step (5, "Amazon.com: Jewelry Made in Italy: Clothing, Shoes & Jewelry - https://www.amazon.com/b?node=19219863011&pf_rd_r=ZS16WVQN9RD996FPB6TH&pf_rd_p=0b9330ec-285a-4f51-9e1c-6765ca451c5f&pd_rd_r=3b9e3cf5-d247-4f50-8d15-a6683fa46846&pd_rd_w=uNsg8&pd_rd_wg=xFg13&ref_=pd_gw_unk");
tab0.Back ();
}