forked from SeleniumHQ/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wd.html
1538 lines (1216 loc) · 56.1 KB
/
wd.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<meta charset=utf-8>
<title>WebDriver</title>
<link rel="icon" href="favicon.ico" type="image/vnd.microsoft.icon">
<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon">
<link rel=stylesheet href=se.css>
<link rel=prev href=start.html title="Getting Started">
<link rel=next href=remote.html title="Remote WebDriver">
<script src=docs.js></script>
<h1>WebDriver</h1>
<p>The biggest change in Selenium recently
has been the inclusion of the WebDriver API.
Driving a browser natively as a user would either locally
or on a remote machine using the Selenium server,
it marks a leap forward in terms of browser automation.
<p>Selenium WebDriver fits in the same role as RC did,
and has incorporated the original 1.x bindings.
It refers to both the language bindings
and the implementations of the individual browser controlling code.
This is commonly referred to as just <em>WebDriver</em>
or sometimes as <em>Selenium 2</em>.
<p>Selenium 1.0 + WebDriver = Selenium 2.0
<ul>
<li>WebDriver is designed in a simpler
and more concise programming interface
along with addressing some limitations in the Selenium-RC API.
<li>WebDriver is a compact object-oriented API
when compared to Selenium 1.0.
<li>It drives the browser much more effectively
and overcomes the limitations of Selenium 1
that affected our functional test coverage,
like the file upload or download, pop-ups, and dialogs barrier.
<li>WebDriver overcomes the limitation of Selenium RC's
<a href="https://en.wikipedia.org/wiki/Same-origin_policy">single-host origin policy.</a>
</ul>
<h2>Understanding The Components</h2>
<p>Building a test suite using WebDriver will require you to understand and effectively use a number of different components. As with everything in software, different people use different terms for the same idea. Below is a breakdown of how terms are used in this description.
<h3>Terminology</h3>
<ul>
<li><strong>API:</strong> Application Programming Interface. This is the set of "commands" you use to manipulate WebDriver.
<li><strong>Library:</strong> A code module which contains the APIs and the code necessary to implement them. Libraries are specific to each language binding, eg .jar files for Java, .dll files for .NET, etc.
<li><strong>Driver:</strong> Responsible for controlling the actual browser. Most drivers are created by the browser vendors themselves. Drivers are generally executable modules that run on the system with the browser itself, not on the system executing the test suite. (Although those may be the same system.) <em>NOTE: Some people refer to the drivers as proxies.</em>
<li><strong>Framework:</strong> An additional library used as a support for WebDriver suites. These frameworks may be test frameworks such as JUnit or NUnit. They may also be frameworks supporting natural language features such as Cucumber or Robotium. Frameworks may also be written and used for things such as manipulating or configuring the system under test, data creation, test oracles, etc.
</ul>
<h3>The Parts and Pieces</h3>
<p>At its minimum, WebDriver talks to a browser through a driver. Communication is two way: WebDriver passes commands to the browser through the driver, and recieves information back via the same route.
</br>
<img src="images/basic_comms.png" width="400px" style="float:none">
<p>The driver is specific to the browser, such as ChromeDriver for Google's Chrome/Chromium, GeckoDriver for Mozilla's Firefox, etc. The driver runs on the same system as the browser. This may, or may not be, the same system where the tests themselves are executing.
<p>This simple example above is <em>direct</em> communication. Communication to the browser may also be <em>remote</em> communication through Selenium Server or RemoteWebDriver. RemoteWebDriver runs on the same system as the driver and the browser.
</br>
<img src="images/remote_comms.png" width="400px" style="float:none">
<p>Remote communication can also take place using Selenium Server or Selenium Grid, both of which in turn talk to the driver on the host system
</br>
<img src="images/remote_comms_server.png" width="400px" >
<h3>Where Frameworks Fit In</h3>
<p>WebDriver has one job and one job only: communicate with the browser via any of the methods above. WebDriver doesn't know a thing about testing: it doesn't know how to compare things, assert pass or fail, and it certainly doesn't know a thing about reporting or Given/When/Then grammar.
<p>This is where various frameworks come in to play. At a minimum you'll need a test framework that matches the language bindings, eg NUnit for .NET, JUnit for Java, RSpec for Ruby, etc.
<p>The test framework is responsible for running and executing your WebDriver and related steps in your tests. As such, you can think of it looking akin to the following image.
</br>
<img src="images/test_framework.png" width="400px" style="float:none">
<p>Natural language frameworks/tools such as Cucumber may exist as part of that Test Framework box in the figure above, or they may wrap the Test Framework entirely in their own implementation.
<h2>Driver requirements</h2>
<p>Through WebDriver, Selenium supports all major browsers on the market
such as Chrom(ium), Firefox, Internet Explorer, Opera, and Safari.
Where possible, WebDriver drives the browser
using the browser's built-in support for automation,
although not all browsers have official support for remote control.
<p>WebDriver's aim is to emulate a real user's interaction
with the browser as closely as possible.
This is possible at varying levels in different browsers.
For more details on the different driver idiosyncracies,
please see <em><a href=drivers.html>Driver Idiosyncracies</a></em>.
<p>Even though all the drivers share a single user-facing interface
for contolling the browser,
they have slightly different ways of setting up browser sessions.
Since many of the driver implementations are provided by third parties,
they are not included in the standard Selenium distribution.
<p>Driver instantiation, profile management, and various browser specific settings
are examples of parameters that have different requirements depending on the browser.
This section explains the basic requirements
for getting you started with the different browsers.
<h3>Adding Executables to your PATH</h3>
<p>Most drivers require an extra executable for Selenium to communicate
with the browser. You can manually specify where the executable lives
before starting WebDriver, but this can make your tests less portable,
as the executables will need to be in the same place on every machine,
or included within your test code repository.
<p>By adding a folder containing WebDriver's binaries to your system's
path, Selenium will be able to locate the additional binaries without
requiring your test code to locate the exact location of the driver.
<ul>
<li>Create a directory to place the executables in, like
<em>C:\WebDriver\bin</em> or <em>/opt/WebDriver/bin</em></li>
<li>Add the directory to your PATH:
<ul>
<li>On Windows - Open a command prompt as administrator
and the run the following command
to permanently add the directory to your path
for all users on your machine:
<pre><code class=bat>setx /m path "%path%;C:\WebDriver\bin\"</code></pre>
<li>Bash users on macOS and Linux - In a terminal:
<pre><code class=shell>export PATH=$PATH:/opt/WebDriver/bin >> ~/.profile</code></pre>
</ul>
<li><p>You are now ready to test your changes.
Close all open command prompts and open a new one.
Type out the name of one of the binaries
in the folder you created in the previous step,
e.g: <pre><code class=shell>chromedriver</code></pre>
If your <var>PATH</var> is configured correctly,
you will see some some output relating to the startup of the driver:
<p><pre><samp>Starting ChromeDriver 2.25.426935 (820a95b0b81d33e42712f9198c215f703412e1a1) on port 9515
Only local connections are allowed.</samp></pre>
<p>You can regain control of your command prompt
by pressing <kbd>Ctrl + C</kbd>.
</ul>
<h3>Quick reference</h3>
<table>
<tr>
<th>Browser
<th>Supported OS
<th>Maintained by
<th>Download
<th>Issue Tracker
</tr>
<tr>
<th>Chromium/Chrome
<td>Windows<br>
macOS<br>
Linux
<td>Google
<td><a href="https://chromedriver.storage.googleapis.com/index.html">Downloads</a>
<td><a href="https://bugs.chromium.org/p/chromedriver/issues/list">Issues</a>
</tr>
<tr>
<th>Firefox
<td>Windows<br>
macOS<br>
Linux
<td>Mozilla
<td><a href=https://github.com/mozilla/geckodriver/releases>Downloads</a>
<td><a href=https://github.com/mozilla/geckodriver/issues>Issues</a>
</tr>
<tr>
<th>Edge
<td>Windows 10
<td>Microsoft
<td><a href=https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/>Downloads</a>
<td><a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/?page=1&q=webdriver">Issues</a>
</tr>
<tr>
<th>Internet Explorer
<td>Windows
<td>Selenium Project
<td><a href=http://selenium-release.storage.googleapis.com/index.html>Downloads</a>
<td><a href=https://github.com/SeleniumHQ/selenium/labels/D-IE>Issues</a>
</tr>
<tr>
<th>Safari
<td>macOS El Capitan and newer
<td>Apple
<td>Built in
<td><a href=https://bugreport.apple.com/logon>Issues</a>
</tr>
<tr>
<th>Opera
<td>Windows<br>
macOS<br>
Linux
<td>Opera
<td><a href=https://github.com/operasoftware/operachromiumdriver/releases>Downloads</a>
<td><a href=https://github.com/operasoftware/operachromiumdriver/issues>Issues</a>
</tr>
</table>
<h4>Chromium/Chrome</h4>
<p>To drive Chrome or Chromium, you have to download
<a href=//sites.google.com/a/chromium.org/chromedriver/downloads>chromedriver</a>
and put it in a folder that is on your system's path.
<p>On Linux or macOS, this means modifying
the <var>PATH</var> environmental variable.
You can see what directories, separated by a colon,
make up your system's path by executing the following command:
<pre><code class=shell>$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin</code></pre>
<p>To include chromedriver on the path if it isn't already,
make sure you include the chromedriver binary's parent directory.
The following line will set the <var>PATH</var> environmental variable
its current content, plus an additional path added after the colon:
<pre><code class=shell>$ export PATH="$PATH:/path/to/chromedriver"</code></pre>
<p>When chromedriver is available on your path,
you should be able to execute the _chromedriver_ executable from any directory.
<p>To instantiate a Chrome/Chromium session, you can do the following:
<pre>
<code class=java>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
WebDriver driver = new ChromeDriver();</code>
<code class=python>#Simple assignment
from selenium.webdriver import Chrome
driver = Chrome()</code>
<code class=python>#Or use the context manager
from selenium.webdriver import Chrome
with Chrome() as driver:
#your code inside this indent</code>
<code class=cs>using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
IWebDriver driver = new ChromeDriver();</code>
<code class=ruby>require "selenium-webdriver"
driver = Selenium::WebDriver.for :chrome</code>
<code class=javascript>const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('chrome').build();
//your code inside this block
})();</code>
</pre>
<p>Remember that you have to set the path to the chromedriver executable.
This is possible using the following line:
<pre>
<code class=java>System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");</code>
<code class=python>Chrome(executable_path='/path/to/chromedriver')</code>
<code class=ruby>Selenium::WebDriver::Chrome.driver_path = "/path/to/chromedriver"</code>
</pre>
<p>The chromedriver is implemented as a WebDriver remote server
that by exposing Chrome's internal automation proxy interface
instructs the browser what to do.
<h3>Firefox</h3>
<p>Starting with Selenium 3, Mozilla has taken over implementation of
Firefox Driver, with <a href=https://github.com/mozilla/geckodriver>geckodriver</a>.
The new driver for Firefox is called geckodriver and works with Firefox
48 and newer. Since the Firefox WebDriver is under development, the
newer the Firefox version the better the support.
<p>As geckodriver is the new default way of launching Firefox, you can
instantiate Firefox in the same way as Selenium 2:
<pre>
<code class=java>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Firefox.FirefoxDriver;
WebDriver driver = new FirefoxDriver();</code>
<code class=python>#Simple assignment
from selenium.webdriver import Firefox
driver = Firefox()</code>
<code class=python>#Or use the context manager
from selenium.webdriver import Firefox
with Firefox() as driver:
#your code inside this indent</code>
<code class=cs>using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
IWebDriver driver = new FirefoxDriver();</code>
<code class=ruby>require "selenium-webdriver"
driver = Selenium::WebDriver.for :firefox</code>
<code class=javascript>const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('firefox').build();
//your code inside this block
})();</code>
</pre>
<p>If you prefer not to set geckodriver's location using PATH,
set the geckodriver binary location programmatically:
<pre>
<code class=java>System.setProperty("webdriver.gecko.driver", "/path/to/geckodriver");</code>
<code class=python>Firefox(executable_path='/path/to/geckodriver')</code>
<code class=ruby>Selenium::WebDriver::Firefox.driver_path = "/path/to/geckodriver"</code>
</pre>
<p>It is also possible to set the property at run time:
<pre><code class=shell>mvn test -Dwebdriver.gecko.driver=/path/to/geckodriver</code></pre>
<p>It is currently possible to revert to the older, more feature complete
Firefox driver, by installing Firefox
<a href="https://ftp.mozilla.org/pub/firefox/releases/47.0.1/">47.0.1</a>
or <a href="https://ftp.mozilla.org/pub/firefox/releases/45.0esr/">45 ESR</a>
and specifying a desired capability of <strong>marionette</strong> as
<strong>false</strong>. Later releases of Firefox are no longer compatible.
<h3>Edge</h3>
<p>Edge is Microsoft's newest browser, included with Windows 10 and Server 2016.
Updates to Edge are bundled with major Windows updates,
so you'll need to download a binary which matches the build number of your currently installed build of Windows.
The <a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/">Edge Developer site</a>
contains links to all the available binaries. Bugs against the EdgeDriver implementation can be raised with
<a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/?page=1&q=webdriver">Microsoft</a>. If you'd like to run tests against Edge, but aren't running Windows 10, Microsoft offer free VMs for testers on the <a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/"> Edge Developer site</a>.
<pre>
<code class=java>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
WebDriver driver = new EdgeDriver();</code>
<code class=python>#Simple assignment
from selenium.webdriver import Edge
driver = Edge()</code>
<code class=python>#Or use the context manager
from selenium.webdriver import Edge
with Edge() as driver:
#your code inside this indent</code>
<code class=cs>using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
IWebDriver driver = new EdgeDriver();</code>
<code class=ruby>require "selenium-webdriver"
driver = Selenium::WebDriver.for :edge</code>
<code class=javascript>const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('MicrosoftEdge').build();
//your code inside this block
})();</code>
</pre>
<p>If Edge driver is not present in your path, you can set the path using the following line:
<pre>
<code class=java>System.setProperty("webdriver.edge.driver", "C:/path/to/MicrosoftWebDriver.exe");</code>
<code class=python>Edge(executable_path='/path/to/MicrosoftWebDriver.exe')</code>
<code class=ruby>Selenium::WebDriver::Edge.driver_path = "C:\path\to\MicrosoftWebDriver.exe"</code>
</pre>
<h3>Internet Explorer</h3>
<p>Internet Explorer was Microsoft's default browser until Windows 10, although it is still included in Windows 10. Internet Explorer Driver is the only driver The Selenium project aims to support the same releases
<a href="https://support.microsoft.com/en-gb/help/17454/lifecycle-support-policy-faq-internet-explorer">
Microsoft considers current</a>. Older releases may work, but will be unsupported.
<p>While the Selenium project provides binaries for both the 32-bit and 64-bit versions of Internet Explorer, there are some <a href="http://jimevansmusic.blogspot.co.uk/2014/09/screenshots-sendkeys-and-sixty-four.html">limitations</a> with Internet Explorer 10 & 11 with the 64-bit driver, but using the 32-bit driver continues to work well. It should be noted that as Internet Explorer preferences are saved against the logged in user's account, some <a href="https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration">additional setup is required</a>.
<pre>
<code class=java>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
WebDriver driver = new InternetExplorerDriver();</code>
<code class=python>#Simple assignment
from selenium.webdriver import Ie
driver = Ie()</code>
<code class=python>#Or use the context manager
from selenium.webdriver import Ie
with Ie() as driver:
#your code inside this indent</code>
<code class=cs>using OpenQA.Selenium;
using OpenQA.Selenium.IE;
IWebDriver driver = new InternetExplorerDriver();</code>
<code class=ruby>require "selenium-webdriver"
driver = Selenium::WebDriver.for :internet_explorer</code>
<code class=javascript>const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('internet explorer').build();
//your code inside this block
})();</code>
</pre>
<p>If Internet Explorer driver is not present in your path, you can set the path using the following line:
<pre>
<code class=java>System.setProperty("webdriver.ie.driver", "C:/path/to/IEDriver.exe");</code>
<code class=python>Ie(executable_path='/path/to/IEDriverServer.exe')</code>
<code class=ruby>Selenium::WebDriver::IE.driver_path = "C:\path\to\IEDriver.exe"</code>
</pre>
Microsoft also offer a WebDriver binary for <a href="https://www.microsoft.com/en-gb/download/details.aspx?id=44069">Internet Explorer 11 on Windows 7 & 8.1</a>. It has not been updated since 2014 and is based of a draft version of the W3 specification. <a href="http://jimevansmusic.blogspot.co.uk/2014/09/using-internet-explorer-webdriver.html">Jim Evans</a> has an excellent writeup on Microsoft's implementation.
<h3>Opera</h3>
<p>Current releases of Opera are built on top of the Chromium engine,
and WebDriver is now supported via the closed-source
<a href="https://github.com/operasoftware/operachromiumdriver/releases">Opera Chromium Driver</a>,
which can be <a href="#adding_executables_to_your_path">added to your PATH</a>
or as a system property.
<p>Instantiating a driver session is similar to Firefox and Chromium:
<pre>
<code class=java>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.opera.OperaDriver;
WebDriver driver = new OperaDriver();</code>
<code class=python>#Simple assignment
from selenium.webdriver import Opera
driver = Opera()</code>
<code class=python>#Or use the context manager
from selenium.webdriver import Opera
with Opera() as driver:
#your code inside this indent</code>
<code class=cs>using OpenQA.Selenium;
using OpenQA.Selenium.Opera;
IWebDriver driver = new OperaDriver();</code>
<code class=ruby>require "selenium-webdriver"
driver = Selenium::WebDriver.for :opera</code>
</pre>
<h3>Safari</h3>
<p>Starting with Safari 10 on macOS El Capitan and Sierra,
WebDriver support is included with each release of the browser.
To enable support:
<ol>
<li>Enable the Developer menu from Safari preferences
<li>Check the <em>Allow Remote Automation</em> option
from with the Develop menu
<li>Run <pre><code class=shell>/usr/bin/safaridriver -p 1337</code></pre> from the terminal
for the first time and type your password
at the prompt to authorise WebDriver
</ol>
<p>You can then start a driver session using:
<pre>
<code class=java>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
WebDriver driver = new SafariDriver();</code>
<code class=python>#Simple assignment
from selenium.webdriver import Safari
driver = Safari()</code>
<code class=python>#Or use the context manager
from selenium.webdriver import Safari
with Safari() as driver:
#your code inside this indent</code>
<code class=cs>using OpenQA.Selenium;
using OpenQA.Selenium.Safari;
IWebDriver driver = new SafariDriver();</code>
<code class=ruby>require "selenium-webdriver"
driver = Selenium::WebDriver.for :safari</code>
<code class=javascript>const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('safari').build();
//your code inside this block
})();</code>
</pre>
<p>Those looking to automate Safari on iOS should look to the
<a href="http://appium.io/">Appium project</a>. Whilst Safari was previously
available for Windows, Apple has long since dropped support, making it
a poor choice of test platform.
<h3>Mock browsers</h3>
<h4>HtmlUnit</h4>
<p>HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you
to invoke pages, fill out forms, click links, etc. It has JavaScript support and is able to work with AJAX libraries,
simulating Chrome, Firefox or Internet Explorer depending on the configuration used. It has been moved to a
<a href="http://htmlunit.sourceforge.net/gettingStarted.html">new</a> location.</p> The source is maintained on svn.
<h4>PhantomJS</h4>
<p>PhantomJS is a headless browser based on Webkit, albeit a version much older than that used by Google Chrome or
Safari. <!-- Unlike HtmlUnit driver, it also supports Javascript ()-->. Whilst historically a popular choice, it would now be
wise to avoid PhantomJS. The project has been unmaintained
<a href="https://groups.google.com/forum/#!topic/phantomjs/9aI5d-LDuNE">since the 5th of August</a>, so whilst the web
will continue to change, PhantomJS will not be updated. This was after Google announced the ability to run Chrome
headlessly, something also now offered by Mozilla's Firefox.</p>
<h2>Browser launching and manipulation</h2>
<!-- #codeExamples -->
<!-- Remember to cover profile and extensions here -->
<h3>Ruby</h3>
<p>Ruby is not installed by default on Windows. Download the latest <a href="http://rubyinstaller.org/downloads">version</a> and run the installer. You can leave all settings at default values, except at the <em>Installation Destination and Optional Tasks</em> screen check <em>Add Ruby executables to your PATH</em> checkbox. To drive any browser, you have to install selenium-webdriver Ruby gem. To install it, open command prompt and type this:
<pre><code class=shell>$ gem install selenium-webdriver</code></pre>
Or, if you use <a href="https://bundler.io">Bundler</a>, add this line to your application's Gemfile:
<pre><code class=ruby always-show>gem "selenium-webdriver"</code></pre>
And then execute the following command in prompt:
<pre><code class=shell>$ bundle install</code></pre>
<h3>Internet Explorer</h3>
<p>Internet Explorer is installed by default on Windows, so no installation is needed. To drive Internet Explorer on Windows, you have to download the latest <a href="http://www.seleniumhq.org/download/">Internet Explorer Driver</a> and put the file into a folder that is in PATH. To find out which directories are in PATH, type <em>echo %PATH%</em> in command prompt.
<pre><code class=bat>$ echo %PATH%
C:\Ruby200\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem</code></pre>
<em>C:\Ruby200\bin</em> looks like a good place. Unzip `IEDriverServer` file and move `IEDriverServer.exe` there.
This should open a new Internet Explorer window:
<pre><code class=ruby always-show>require "selenium-webdriver"
driver = Selenium::WebDriver.for :internet_explorer</code></pre>
<h2>Browser Navigation</h2>
<h3>Navigate To</h3>
<p>The first thing you will want to do after launching a browser is to
open your website. This can be achieved in a single line:
<pre>
<code class=java>
//Convenient
driver.get("https://www.seleniumhq.org");
//Longer way
driver.navigate().to("https://seleniumhq.github.io/docs/");
</code>
<code class=python>driver.get("https://www.seleniumhq.org")</code>
<code class=ruby>
# Convenient
driver.get 'https://www.seleniumhq.org'
# Longer way
driver.navigate.to 'https://seleniumhq.github.io/docs/'
</code>
<code class=cs>driver.Navigate().GoToUrl(@"http://google.com");</code>
<code class=javascript>driver.get("https://seleniumhq.github.io/docs/");</code>
</pre>
<h3>Get Current URL</h3>
<p>You can read the current URL from the browser's address bar
using:</p>
<pre>
<code class=java>driver.getCurrentUrl();</code>
<code class=python>driver.current_url</code>
<code class=ruby>driver.current_url</code>
<code class=cs>driver.Url;</code>
<code class=javascript>await driver.getCurrentUrl();</code>
</pre>
<h3>Back</h3>
<p>Pressing the browser's back button:
<pre>
<code class=java>driver.navigate().back();</code>
<code class=python>driver.back()</code>
<code class=ruby>driver.navigate.back</code>
<code class=cs>driver.Navigate().Back();</code>
<code class=javascript>driver.back();</code>
</pre>
<h3>Forward</h3>
<p>Pressing the browser's forward button:
<pre>
<code class=java>driver.navigate().forward();</code>
<code class=python>driver.forward()</code>
<code class=ruby>driver.navigate.forward</code>
<code class=cs>driver.Navigate().Forward();</code>
<code class=javascript>driver.forward();</code>
</pre>
<h3>Refresh</h3>
<p>Refresh the current page:
<pre>
<code class=java>driver.navigate().refresh();</code>
<code class=python>driver.refresh()</code>
<code class=ruby>driver.navigate.refresh</code>
<code class=cs>driver.Navigate().Refresh();</code>
<code class=javascript>driver.refresh();</code>
</pre>
<h3>Get Title</h3>
<p>You can read the current page title from the browser:</p>
<pre>
<code class=java>driver.getTitle();</code>
<code class=python>driver.title</code>
<code class=ruby>driver.title</code>
<code class=cs>driver.Title;</code>
<code class=javascript>driver.getTitle();</code>
</pre>
<h2>Windows and tabs</h2>
<p>WebDriver doesn't make the distinction between windows and tabs. If
your site opens a new tab or window, Selenium will let you work with it
using a window handle. Each window has a unique identifier which remains
persistent in a single session. You can get the window handle of the
current window by using:</p>
<pre>
<code class=java>driver.getWindowHandle();</code>
<code class=python>driver.current_window_handle</code>
<code class=cs>driver.CurrentWindowHandle</code>
<code class=ruby>driver.window_handle</code>
<code class=javascript>await driver.getWindowHandle();</code>
</pre>
<h3>Switching windows or tabs</h3>
<p>Clicking a link which opens in a <a href="https://seleniumhq.github.io/docs/" target="_blank">
new window</a> will visible focus the new window or tab on screen, but
WebDriver will not know which window the Operating System considers
active. To work with the new window you will need to switch to it. If
you have only two tabs or windows open, and you know which window you
start with, by the process of elimination you can loop over both windows
or tabs that WebDriver can see, and switch to the one which is not the
original.</p>
<pre>
<code class=java>//Store the ID of the original window
String originalWindow = driver.getWindowHandle();
//Check we don't have other windows open already
assert driver.getWindowHandles().size() == 1;
//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click();
//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2));
//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
if(!originalWindow.contentEquals(windowHandle)) {
driver.switchTo().window(windowHandle);
break;
}
}
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));</code>
<code class=python>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Start the driver
with webdriver.Firefox() as driver:
# Open URL
driver.get("https://seleniumhq.github.io/docs/wd.html")
# Setup wait for later
wait = WebDriverWait(driver, 10)
# Store the ID of the original window
original_window = driver.current_window_handle
# Check we don't have other windows open already
assert len(driver.window_handles) == 1
# Click the link which opens in a new window
driver.find_element_by_link_text("new window").click()
# Wait for the new window or tab
wait.until(EC.number_of_windows_to_be(2))
# Loop through until we find a new window handle
for window_handle in driver.window_handles:
if window_handle != original_window:
driver.switch_to.window(window_handle)
break
# Wait for the new tab to finish loading content
wait.until(EC.title_is("Selenium documentation"))</code>
<code class=cs>//Store the ID of the original window
String originalWindow = driver.CurrentWindowHandle;
//Check we don't have other windows open already
Assert.AreEqual(driver.WindowHandles.Count, 1);
//Click the link which opens in a new window
driver.FindElement(By.LinkText("new window")).Click();
//Wait for the new window or tab
wait.Until(wd => wd.WindowHandles.Count == 2);
//Loop through until we find a new window handle
foreach(String window in driver.WindowHandles)
{
if(originalWindow != window)
{
driver.SwitchTo().Window(window);
break;
}
}
//Wait for the new tab to finish loading content
wait.Until(wd => wd.Title == "Selenium documentation");</code>
<code class=ruby>#Store the ID of the original window
original_window = driver.window_handle
#Check we don't have other windows open already
assert(driver.window_handles.length == 1, 'Expected one window')
#Click the link which opens in a new window
driver.find_element(link: 'new window').click
#Wait for the new window or tab
wait.until { driver.window_handles.length == 2 }
#Loop through until we find a new window handle
driver.window_handles.each do |handle|
if handle != original_window
driver.switch_to.window handle
break
end
end
#Wait for the new tab to finish loading content
wait.until { driver.title == 'Selenium documentation'}
</code>
<code class=javascript>//Store the ID of the original window
const originalWindow = await driver.getWindowHandle();
//Check we don't have other windows open already
assert((await driver.getAllWindowHandles()).length === 1);
//Click the link which opens in a new window
await driver.findElement(By.linkText('new window')).click();
//Wait for the new window or tab
await driver.wait(function() {
return driver.getAllWindowHandles().then(function(windows) {
return windows.length === 2;
});
}, 10000);
//Loop through until we find a new window handle
const windows = (await driver.getAllWindowHandles());
for (let i = 0; i < windows.length; i++) {
if(windows[i]!==originalWindow) {
await driver.switchTo().window(windows[i]);
}
}
//Wait for the new tab to finish loading content
await driver.wait(until.titleIs('Selenium documentation'), 10000);</code>
</pre>
<h3>Closing a window or tab</h3>
<p>When you are finished with a window or tab <em>and</em> it is not the
last window or tab open in your browser, you should close it and switch
back to the window you were using previously. Assuming you followed the
code sample in the previous section you will have the previous window
handle stored in a variable. Put this together and you will get:</p>
<pre>
<code class=java>//Close the tab or window
driver.close();
//Switch back to the old tab or window
driver.switchTo().window(originalWindow);</code>
<code class=python>#Close the tab or window
driver.close()
#Switch back to the old tab or window
driver.switch_to.window(original_window)</code>
<code class=cs>//Close the tab or window
driver.Close();
//Switch back to the old tab or window
driver.SwitchTo().Window(originalWindow);</code>
<code class=ruby>#Close the tab or window
driver.close
#Switch back to the old tab or window
driver.switch_to.window original_window</code>
<code class=javascript>//Close the tab or window
await driver.close();
//Switch back to the old tab or window
await driver.switchTo().window(originalWindow);
</code>
</pre>
<p>Forgetting to switch back to another window handle after closing a
window will leave WebDriver executing on the now closed page, and will
trigger a <strong>No Such Window Exception</strong>. You must switch
back to a valid window handle in order to continue execution.</p>
<h3>Quiting the browser at the end of a session</h3>
<p>When you are finished with the browser session you should call quit,
instead of close:
<pre>
<code class=java>driver.quit();</code>
<code class=python>driver.quit()</code>
<code class=cs>driver.Quit();</code>
<code class=ruby>driver.quit</code>
<code class=javascript>await driver.quit();</code>
</pre>
<p>Quit will:
<ul>
<li>Close all the windows and tabs associated with that WebDriver
session</li>
<li>The browser process</li>
<li>The background driver process</li>
<li>Notify Selenium Grid that the browser is no longer in use so it can
be used by another session (if you are using Selenium Grid).</li>
</ul>
<p>Failure to call quit will leave extra background processes and ports
running on your machine which could cause you problems later.</p>
<p>Some test frameworks offer methods and annotations which you can hook
into to tear down at the end of a test.</p>
<pre>
<code class=java>/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/
@AfterAll
public static void tearDown() {
driver.quit();
}</code>
<code class=cs>/*
Example using Visual Studio's UnitTesting
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx
*/
[TestCleanup]
public void TearDown()
{
driver.Quit();
}</code>
</pre>
<p>If not running WebDriver in a test context, you may consider using
try / finally which is offered by most languages so that an exception
will still clean up the WebDriver session.</p>
<pre>
<code class=java>try {
//WebDriver code here...
} finally {
driver.quit();
}</code>
<code class=python>try:
#WebDriver code here...
finally:
driver.quit()</code>
<code class=cs>try {
#WebDriver code here...
} finally {
driver.Quit();
}</code>
<code class=ruby>begin
#WebDriver code here...
ensure
driver.quit
end</code>
<code class=javascript>try {
//WebDriver code here...
} finally {
await driver.quit();
}</code>
</pre>
<p>Python's WebDriver now supports the python context manager,
which when using the with keyword can automatically quit the driver at
the end of execution.</p>
<pre>
<code class=python always-show>with webdriver.Firefox() as driver:
#WebDriver code here...
#WebDriver will automatically quit after indentation</code>
</pre>
<h2>Frames and Iframes</h2>
<p>Frames are a now deprecated means of building a site layout from
multiple documents on the same domain. You are unlikely to work with
them unless you are working with an pre HTML5 webapp. Iframes allow
the insertion of a document from an entirely different domain, and are
still commonly used.</p>
<p>If you need to work with frames or iframes, Webdriver allows you to
work with them in the same way. Consider a button within an iframe.
If we inspect the element using the browser development tools, we might
see the following:</p>
<pre><code class=html><div id="modal">
<iframe id="buttonframe" name="myframe" src="https://seleniumhq.github.io/docs/iframe.html">
<button>Click here</button>
</iframe>
</div>
</code></pre>
<p>If it wasn't for the iframe we would expect to click on the button
using something like:</p>
<pre><code class=java>//This won't work
driver.findElement(By.tagName("button")).click();
</code></pre>
<p>However, if there are no buttons outside of the iframe, you might
instead get a <em>no such element</em> error. This happens because Selenium is
only aware of the elements in the top level document. To interact with
the button, we will need to first switch to the frame, in a similar way
to how we switch windows. Webdriver offers three ways of switching to
a frame.</p>
<h3>Using a webelement</h3>
<p>Switching using a webelement is the most flexible option. You can
find the frame using your preferred selector and switch to it.</p>
<pre>
<code class=java>//Store the web element
WebElement iframe = driver.findElement(By.cssSelector("#modal>iframe"));
//Switch to the frame
driver.switchTo().frame(iframe);
//Now we can click the button
driver.findElement(By.tagName("button")).click();
</code>
</pre>
<h3>Using a name or ID</h3>
<p>If your frame or iframe has a id or name attribute, this can be used
instead. If the name or ID is not unique on the page, then the first
one found will be switched to.</p>
<pre>
<code class=java>//Using the ID
driver.switchTo().frame("buttonframe");
//Or using the name instead
driver.switchTo().frame("myframe");
//Now we can click the button
driver.findElement(By.tagName("button")).click();</code>
</pre>
<h3>Using an index</h3>
<p>It is also possible to use the index of the frame, such as can be
queried using <em>window.frames</em> in javascript.</p>
<pre>
<code class=java>//Switches to the second frame
driver.switchTo().frame(1);</code>