Al editar scripts en EveryStep Scripting Tool Desktop, puede agregar un código personalizado de C. Consulte Modelo de objetos de la herramienta de scripting EveryStep: clases, métodos, propiedades, etc . para obtener más información sobre la personalización del script EveryStep.

Los scripts que se han editado con código C# personalizado requieren una aprobación de nuestro equipo de soporte técnico antes de guardarse. Cada vez que agregue un código C# personalizado o edite un script que contenga código C# personalizado, el script se enviará automáticamente para su aprobación. Tenga en cuenta que nuestro equipo puede tardar algún tiempo en revisar y aprobar el script para su uso.

Estos son algunos ejemplos de cómo agregar C# a un script para usar sentencias condicionales y variables definidas aleatoriamente:

Ejemplos de instrucciones condicionales

Anulación de la ejecución del script en un error de validación de contenido

Step (1, "test - https://www.test.com");
tab0 = Tabs.NewTab ();
tab0.GoTo ("https://www.test.com");
if ( !tab0.Text.Contains("<KEYWORD>"))
{
return;
}
Por ejemplo, para anular el script si no se encuentra la palabra clave “Login“, agregue:
if (!tab0.Text.Contains("Login"))

Cierre de ventanas emergentes condicionales si aparecen

Las condiciones de reproducción del script pueden variar según las regiones geográficas, el tiempo, etc. Por lo tanto, algunos contenidos, como las ventanas emergentes, se pueden mostrar en función de las condiciones mientras reproducimos el script. Para especificar cómo desea administrar el contenido condicional en el sitio web de destino, agregue la instrucción if al script EveryStep.

Por ejemplo, para cerrar una ventana emergente si se muestra en la página durante una reproducción de script y navegar a una nueva página

  1. Grabe el script con la ventana emergente que se muestra en la página.
  2. Alternativamente: Si tiene Xpath para ubicar el botón “Cerrar” en la página de destino, puede grabar el script sin la ventana emergente.
  3. Agregue la instrucción if en el paso donde se espera que aparezca la ventana emergente. Utilice el botón “Cerrar” Xpath para especificar la condición.

Tenga en cuenta que usamos el método WaitForElement en la expresión de prueba “if” para esperar a que se cargue la ventana emergente:

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");

Agregar el artículo al carrito de compras o a la lista de espera si el artículo no está disponible

Si… else permite que su script lleve a cabo acciones específicas como clics de botones, verificaciones de casillas de verificación, navegación a otra URL, etc. basado en la condición especificada. Por ejemplo, puede registrar una transacción “agregar al carrito de compras” y desea que el script agregue un artículo al carrito o, si está agotado, a una lista de espera. Puede hacer esto agregando un si… Declaración else:

  1. Registre la transacción del carrito de compras.
  2. Para especificar la expresión de prueba, seleccione el elemento que indica que el artículo está en stock, por ejemplo, el botón “Comprar ahora”.
  3. Especifique la instrucción “if” después de navegar a la página del elemento mediante tab0. Método WaitForElement (TimeSpan timeout, string xpath) con el botón “Comprar ahora” Xpath.
  4. Especifique la acción que se va a ejecutar si el elemento está disponible como instrucción “if”. Por ejemplo, el clic “Comprar ahora”.
  5. Especifique la acción que se ejecutará si el artículo está agotado (no se detectó el botón “Comprar ahora”) como la instrucción “else”. Por ejemplo, el clic “Agregar a la lista”.

Consejos

Para especificar acciones de flujo alternativas, registre las acciones además del flujo predeterminado dentro del mismo script. A continuación, utilice las líneas relacionadas en la instrucción “else”.

Compruebe el ejemplo que se proporciona a continuación.

// 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&");

Aleatorización de datos

Aleatorización de correo electrónico para procesos de registro

Para usar correos electrónicos generados aleatoriamente en el proceso de registro, puede declarar una nueva variable con el valor generado aleatoriamente similar al siguiente:

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

Utilice la variable como parámetro del método TypeText para el campo de correo electrónico como se muestra a continuación:

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 ();

Entrar entre 18 y 12 años.

// 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());

Elegir al azar el género masculino o femenino

// 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());
}

Elegir un artículo al azar de un catálogo de productos en línea

Para crear un script que elija repetidamente elementos aleatorios de un catálogo en línea, use el ejemplo que se proporciona a continuación. Tenga en cuenta que se recomienda registrar primero varios clics de elementos para facilitar la edición del origen más adelante.

// 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 ();
}