JS dialogs such as alert, confirm, and prompt can be easily and concisely processed in selenium webdriveriver. The following HTML code is used as an example:
Example.html
<HTML>
<Head>
<Title> alert </title>
</Head>
<Body>
<Input id = "alert" value = "alert" type = "button" onclick = "alert ('Hello! Please press OK to continue! '); "/>
<Input id = "Confirm" value = "Confirm" type = "button" onclick = "Confirm ('OK? '); "/>
<Inputid = "prompt" value = "prompt" type = "button" onclick = "Var name = prompt ('Enter the content: ',' enter
Content '); document. Write (name) "/>
</Body>
</Html>
The preceding HTML code displays three buttons on the page. Click them to bring up the alert, confirm, and prompt dialog boxes. If you enter the text in the prompt dialog box and click OK, the page is refreshed to display the text.
The code for selenium webdriveriver to process these bullet layers is as follows:
Import org. openqa. Selenium. Alert;
Import org. openqa. Selenium.;
Import org. openqa. Selenium. webdriveriver;
Import org. openqa. Selenium. Firefox. firefoxdriveriver;
Public class alertpop {
/**
* @ Author tyf
*/
Publicstatic void main (string [] ARGs ){
// Todo auto-generated method stub
Webdriveriver driver = new firefoxdriveriver ();
Stringurl = "file: // C:/selenium/example.html"; // path of the example.html File
Driver. Get (URL );
// Click the first button to output the text above the dialog box
Driver. findelement (by. ID ("alert"). Click ();
Alertalert = driver. switchto (). Alert ();
Stringtext = alert. gettext ();
System. Out. println (text );
Alert. Dismiss (); // close alert
// Click the second button, output the text above the dialog box, and then confirm
Driver. findelement (by. ID ("Confirm"). Click ();
Alertconfirm = driver. switchto (). Alert ();
Stringtext1 = confirm. gettext ();
System. Out. println (text1 );
Confirm. Accept ();
// Click the third button, enter your name, and click OK.
Driver. findelement (by. ID ("prompt"). Click ();
Alertprompt = driver. switchto (). Alert ();
Stringtext2 = prompt. gettext ();
System. Out. println (text2 );
Prompt. sendkeys ("jarvi ");
Prompt. Accept ();
}
}
From the above code, we can see that driver. switchto (). Alert (); this sentence can get the object of the alert \ confirm \ prompt dialog box, and then use its method to operate on it. The dialog box operation methods include:
- Gettext () to get the text content
- Accept () is equivalent to clicking "OK"
- Dismiss () is equivalent to clicking the "cancel" dialog box
- Sendkeys () input value. This alert \ confirm cannot be used without a dialog box. Otherwise, an error is returned.