-
Notifications
You must be signed in to change notification settings - Fork 96
/
01-user-guide.adoc
3065 lines (2405 loc) · 92 KB
/
01-user-guide.adoc
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
// NOTE: release workflow automatically updates etaoin versions in this file
// NOTE: many of the clojure code blocks in this file are tested via lread/test-doc-block
= User Guide
:toclevels: 5
:toc:
:lib-version: 1.0.40
:project-src-coords: clj-commons/etaoin
:project-mvn-coords: etaoin/etaoin
:url-webdriver: https://www.w3.org/TR/webdriver/
:url-sample-page: /doc/user-guide-sample.html
:url-doc: https://cljdoc.org/d/{project-mvn-coords}
:url-tests: /test/etaoin/api_test.clj
:url-slack: https://clojurians.slack.com/archives/C7KDM0EKW
== Introduction
Etaoin offers the Clojure community a simple way to script web browser interactions from Clojure and Babashka.
It is a thin abstraction atop the link:{url-webdriver}[W3C WebDriver protocol] that also endeavors to resolve real-world nuances and implementation differences.
=== History
Ivan Grishaev (https://github.com/igrishaev[@igrishaev]) created Etaoin and published its first release to Clojars in Feb of 2017.
He and his band of faithful contributors grew Etaoin into a well respected goto-library for browser automation.
In May 2022, finding his time had gravitated more to back-end development, Ivan offered Etaoin for adoption to clj-commons.
It is now currently under the loving care of https://github.com/lread[@lread] and https://github.com/borkdude[@borkdude].
=== Interesting Alternatives
If Etaoin is not your cup of tea, you might also consider:
Clojure based:
* https://github.com/pfeodrippe/wally[Wally] - A Clojure Playwright wrapper
* https://github.com/tatut/clj-chrome-devtools[clj-chrome-devtools] - Clojure API for controlling a Chrome DevTools remote
Other:
* https://www.selenium.dev/[Selenium] - A browser automation framework and ecosystem
* https://playwright.dev/[Playwright] - Reliable end-to-end testing for modern web apps
* https://pptr.dev/[Puppeteer] - A high-level API to control Chrome/Chromium over the DevTools Protocol
[[supported-os-browser]]
=== Supported OSes & Browsers
Etaoin's test suite covers the following OSes and browsers for both Clojure and Babashka:
|===
| OS | Chrome | Firefox | Safari | Edge
| Linux (ubuntu)
| yes
| yes
| -
| -
| macOS
| yes
| yes
| yes
| yes
| Windows
| yes
| yes
| -
| yes
|===
NOTE: We did once test against PhantomJS, but since work has long ago stopped on this project, we have dropped testing
== Installation
There are two steps to installation:
. Add the `etaoin` library as a dependency to your project
. Install the WebDriver for each web browser that you want to control with Etaoin
=== Add the Etaoin Library Dependency
==== For Clojure Users
Etaoin supports Clojure v1.9 and above.
Add the following into the `:dependencies` vector in your `project.clj` file:
[source,clojure,subs="attributes+"]
----
[etaoin "{lib-version}"]
----
//:test-doc-blocks/skip
Or the following under `:deps` in your `deps.edn` file:
[source,clojure,subs="attributes+"]
----
etaoin/etaoin {:mvn/version "{lib-version}"}
----
==== For Bababashka Users
We recommend the current release of https://book.babashka.org/#_installation[babashka].
Add the following under `:deps` to your `bb.edn` file:
//:test-doc-blocks/skip
[source,clojure,subs="attributes+"]
----
etaoin/etaoin {:mvn/version "{lib-version}"}
----
[TIP]
====
Babashka uses https://github.com/ptaoussanis/timbre[timbre] for logging.
Timbre's default logging level is debug.
For a quieter Etaoin experience when using babashka, set the timbre default log level to info:
//:test-doc-blocks/skip
[source,clojure]
----
(require '[taoensso.timbre :as timbre])
(timbre/set-level! :info)
----
====
:url-webdriver: https://www.w3.org/TR/webdriver/
:url-tests: https://github.com/{project-src-coords}/blob/master/test/etaoin/api_test.clj
:url-chromedriver: https://sites.google.com/chromium.org/driver/
:url-chromedriver-dl: https://sites.google.com/chromium.org/driver/downloads
:url-geckodriver-dl: https://github.com/mozilla/geckodriver/releases
:url-phantom-dl: http://phantomjs.org/download.html
:url-webkit: https://webkit.org/blog/6900/webdriver-support-in-safari-10/
:url-edge-dl: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
[[install-webdrivers]]
=== Installing the Browser WebDrivers
Etaoin controls web browsers via their WebDrivers.
Each browser has its own WebDriver implementation that must be installed.
[TIP]
====
If it is not already installed, you will need to install the web browser too (Chrome, Firefox, Edge).
This is usually via a download from its official site.
Safari comes bundled with macOS.
====
[TIP]
====
WebDrivers and browsers are updated regularly to fix bugs.
Use current versions.
====
Some ways to install WebDrivers:
* Google link:{url-chromedriver}[Chrome Driver] +
** macOS: `brew install chromedriver`
** Windows: `scoop install chromedriver`
** Download: link:{url-chromedriver-dl}[Official Chromedriver download]
* Geckodriver for Firefox
** macOS: `brew install geckodriver`
** Windows: `scoop install geckodriver`
** Download: link:{url-geckodriver-dl}[Official geckodriver release page]
* Safari Driver
** macOS only: Set up Safari options as the link:{url-webkit}[Webkit page] instructs (scroll down to "Running the Example in Safari" section).
* Microsoft Edge Driver
** macos: (download manually)
** Windows: `scoop install edgedriver` +
Edge and `msedgedriver` must match so you might need to specify the version:
`scoop install [email protected]`
** Download: link:{url-edge-dl}[Official Microsoft download site]
* Phantom.js browser +
(obsolete, no longer tested)
** macOS: `brew install phantomjs`
** Windows: `scoop install phantomjs`
** Download: link:{url-phantom-dl}[Official PhantomJS download site]
Check your WebDriver installations launching by launching these commands.
Each should start a process that includes its own local HTTP server.
Use Ctrl-C to terminate.
[source,bash]
----
chromedriver
geckodriver
safaridriver -p 0
msedgedriver
phantomjs --wd
----
You can optionally run the Etaoin test suite to verify your installation.
TIP: Some Etaoin API tests rely on ImageMagick.
Install it prior to running test.
From a clone of the https://github.com/clj-commons/etaoin[Etaoin GitHub repo]
* To check tools of interest to Etaoin:
+
[source,bash]
----
bb tools-versions
----
* Run all tests:
+
[source,bash]
----
bb test all
----
* For a smaller sanity test, you might want to run api tests against browsers you are particularly intested in. Example:
+
[source,bash]
----
bb test api --browser chrome
----
During the test run, browser windows will open and close in series.
The tests use a local handcrafted HTML file to validate most interactions.
See <<troubleshooting>> if you have problems - or reach out on link:{url-slack}[Clojurians Slack #etaoin] or https://github.com/clj-commons/etaoin/issues[GitHub issues].
== Getting Started
The great news is that you can automate your browser directly from your Babashka or Clojure REPL.
Let's interact with Wikipedia:
// A little invisible codeblock for some setup
ifdef::env-test-doc-blocks[]
[source,clojure]
----
(require '[babashka.fs :as fs])
;; for better test-doc-block reporting when running generated tests
(require '[etaoin.test-report])
;; for screenshots save dir (dir must currently exist)
(fs/create-dirs "target/etaoin-play")
----
endif::[]
[source,clojure]
----
(require '[etaoin.api :as e]
'[etaoin.keys :as k])
;; Start WebDriver for Firefox
(def driver (e/firefox)) ;; a Firefox window should appear
;; let's perform a quick Wiki session
;; navigate to wikipedia
(e/go driver "https://en.wikipedia.org/")
;; wait for the search input to load
(e/wait-visible driver [{:id :simpleSearch} {:tag :input :name :search}])
;; search for something interesting
(e/fill driver {:tag :input :name :search} "Clojure programming language")
(e/wait driver 1)
(e/fill driver {:tag :input :name :search} k/enter)
(e/wait-visible driver {:class :mw-search-results})
;; click on first match
(e/click driver [{:class :mw-search-results} {:class :mw-search-result-heading} {:tag :a}])
(e/wait-visible driver {:id :firstHeading})
;; check our new url location
(e/get-url driver)
;; => "https://en.wikipedia.org/wiki/Clojure"
;; and our new title
(e/get-title driver)
;; => "Clojure - Wikipedia"
;; does page have Clojure in it?
(e/has-text? driver "Clojure")
;; => true
;; navigate through history
(e/back driver)
(e/forward driver)
(e/refresh driver)
(e/get-title driver)
;; => "Clojure - Wikipedia"
;; let's explore the info box
;; What's its caption? Let's select it with a css query:
(e/get-element-text driver {:css "table.infobox caption"})
;; => "Clojure"
;; Ok,now let's try something trickier
;; Maybe we are interested what value the infobox holds for the Family row:
(let [wikitable (e/query driver {:css "table.infobox.vevent tbody"})
row-els (e/children driver wikitable {:tag :tr})]
(for [row row-els
:let [header-col-text (e/with-http-error
(e/get-element-text-el driver
(e/child driver row {:tag :th})))]
:when (= "Family" header-col-text)]
(e/get-element-text-el driver (e/child driver row {:tag :td}))))
;; => ("Lisp")
;; Etaoin gives you many options, we can do the same-ish in one swoop in XPath:
(e/get-element-text driver "//table[@class='infobox vevent']/tbody/tr/th[text()='Family']/../td")
;; => "Lisp"
;; When we are done we quit, which stops the Firefox WebDriver
(e/quit driver) ;; the Firefox Window should close
----
Most api functions require the driver as the first argument.
The `doto` macro can give your code a DSL feel.
A portion of the above rewritten with `doto`:
[source,clojure]
----
(require '[etaoin.api :as e]
'[etaoin.keys :as k])
(def driver (e/firefox))
(doto driver
(e/go "https://en.wikipedia.org/")
(e/wait-visible [{:id :simpleSearch} {:tag :input :name :search}])
(e/fill {:tag :input :name :search} "Clojure programming language")
(e/wait 1)
(e/fill {:tag :input :name :search} k/enter)
(e/wait-visible {:class :mw-search-results})
(e/click [{:class :mw-search-results} {:class :mw-search-result-heading} {:tag :a}])
(e/wait-visible {:id :firstHeading})
(e/quit))
----
== Playing Along in your REPL
We encourage you to try the examples in from this user guide in your REPL.
The Interwebs is constantly changing.
This makes testing against live sites impractical.
The code in this user guide has instead been tested to work against our link:{url-sample-page}[little sample page].
Until we figure out something more clever, it might be easiest to clone the etaoin GitHub repository and run a REPL from there.
Unless otherwise directed, our examples throughout the rest of this guide will assume you've already executed the equivalent of:
[source,clojure]
----
(require '[etaoin.api :as e]
'[etaoin.keys :as k]
'[clojure.java.io :as io])
(def sample-page (-> "doc/user-guide-sample.html" io/file .toURI str))
(def driver (e/chrome)) ;; or replace chrome with your preference
(e/go driver sample-page)
----
== More Getting Started
You can use `fill-multi` to shorten the code like so:
[source,clojure]
----
(e/fill driver :uname "username")
(e/fill driver :pw "pass")
(e/fill driver :text "some text")
;; let's get what we just set:
(mapv #(e/get-element-value driver %) [:uname :pw :text])
;; => ["username" "pass" "some text"]
----
into:
[source,clojure]]
----
;; issue a browser refresh
(e/refresh driver)
(e/fill-multi driver {:uname "username2"
:pw "pass2"
:text "some text2"})
;; to get what we just set:
(mapv #(e/get-element-value driver %) [:uname :pw :text])
;; => ["username2" "pass2" "some text2"]
----
If any exception occurs during a browser session, the WebDriver process might hang until you kill it manually.
To prevent that, we recommend the `with-<browser>` macros:
[source,clojure]
----
(e/with-firefox driver
(doto driver
(e/go "https://google.com")
;; ... your code here
))
----
This will ensure that the WebDriver process is closed regardless of what happens.
== Unit Tests as Docs
The sections that follow describe how to use Etaoin in more depth.
In addition to these docs, the link:{url-tests}[Etaoin api tests] are also a good reference.
== Creating and Quitting the Driver
Etaoin comes with many options to create a WebDriver instance.
TIP: As previously mentioned, we recommend the `with-<browser>` convention when you need proper cleanup.
Let's say we want to create a chrome headless driver:
// let's not pollute our main test-doc-block ns with these driver vars:
//{:test-doc-blocks/test-ns user-guide-driver-creation-test}
[source,clojure]
----
(require '[etaoin.api :as e])
;; at the base we have:
(def driver (e/boot-driver :chrome {:headless true}))
;; do stuff
(e/quit driver)
;; This can also be expressed as:
(def driver (e/chrome {:headless true}))
;; do stuff
(e/quit driver)
;; Or...
(def driver (e/chrome-headless))
;; do stuff
(e/quit driver)
----
The `with-<browser>` functions handle cleanup nicely:
[source,clojure]
----
(e/with-chrome {:headless true} driver
(e/go driver "https://clojure.org"))
(e/with-chrome-headless driver
(e/go driver "https://clojure.org"))
----
Replace `chrome` with `firefox`, `edge` or `safari` for other variants.
See link:{url-doc}[API docs] for details.
See <<driver-options>> for all options available when creating a driver.
== Selecting Elements [[querying]]
Queries (aka selectors) are used to select the elements on the page that Etaoin will interact with.
[source,clojure]]
----
;; let's start anew by refreshing the page:
(e/refresh driver)
;; select the element with an html attribute id of 'uname' and fill it with text:
(e/fill driver {:id "uname"} "Etaoin")
;; select the first element with an html button tag and click on it:
(e/click driver {:tag :button})
----
[TIP]
====
* A query returns a unique element identifier typically meaningful only as a selector to other functions it is passed to.
* Many functions accept a query directly. For example:
+
[source,clojure]]
----
;; specifying query directly
(e/get-element-text driver {:tag :button})
;; => "Submit Form"
;; specifying the result of a query (notice the `-el` fn variant here)
(e/get-element-text-el driver (e/query driver {:tag :button}))
;; => "Submit Form"
----
====
[TIP]
====
An exception is thrown if a query does not find an element.
Use exists? to check for element existence:
[source,clojure]
----
(e/exists? driver {:tag :button})
;; => true
(e/exists? driver {:id "wont-find-me"})
;; => false
----
====
=== Simple Queries, XPath, CSS
:xpath-sel: https://www.w3schools.com/xml/xpath_syntax.asp
:css-sel: https://www.w3schools.com/cssref/css_selectors.asp
* `:active` finds the current active element.
The Google page, for example, automatically places the focus on the search input.
So there is no need to click on it first:
+
[source,clojure]
----
(e/go driver "https://google.com")
(e/fill driver :active "Let's search for something" k/enter)
----
* any other keyword is translated to an html id attribute:
+
[source,clojure]
----
(e/go driver sample-page)
(e/fill driver :uname "Etaoin" k/enter)
;; alternatively you can:
(e/fill driver {:id "uname"} "Etaoin Again" k/enter)
----
* a string containing an link:{xpath-sel}[XPath] expression.
(Be careful when writing XPath manually, see <<troubleshooting>>.)
Here we find an `input` tag with an attribute `id` of `uname` and an attribute `name` of `username`:
+
[source,clojure]
----
(e/refresh driver)
(e/fill driver ".//input[@id='uname'][@name='username']" "XPath can be tricky")
;; let's check if that worked as expected:
(e/get-element-value driver :uname)
;; => "XPath can be tricky"
----
* a map with either `:xpath` or `:css` key with a string in corresponding syntax:
+
[source,clojure]
----
(e/refresh driver)
(e/fill driver {:xpath ".//input[@id='uname']"} "XPath selector")
(e/fill driver {:css "input#uname[name='username']"} " CSS selector")
;; And here's what we should see in username input field now:
(e/get-element-value driver :uname)
;; => "XPath selector CSS selector"
----
+
This link:{css-sel}[CSS selector reference] may be of help.
=== Map Syntax Queries
A query can also be a map that represents an XPath expression as data.
The rules are:
* A `:tag` key represents a tag's name.
Defaults to `*`.
* An `:index` key expands into the trailing XPath `[x]` clause.
Useful when you need to select a third row from a table, for example.
* Any non-special key represents an attribute and its value.
* `:fn/` is a prefix followed by a supported query function.
Examples:
* find the first `div` tag
+
[source,clojure]
----
(= (e/query driver {:tag :div})
;; equivalent via xpath:
(e/query driver ".//div"))
;; => true
----
* find the n-th (1-based) `div` tag
+
[source,clojure]
----
(= (e/query driver {:tag :div :index 1})
;; equivalent via xpath:
(e/query driver ".//div[1]"))
;; => true
----
* find the tag `a` where the class attribute equals to `active`
+
[source,clojure]
----
(= (e/query driver {:tag :a :class "active"})
;; equivalent xpath:
(e/query driver ".//a[@class='active']"))
----
* find a form by its attributes:
+
[source,clojure]
----
(= (e/query driver {:tag :form :method :GET :class :formy})
;; equivalent in xpath:
(e/query driver ".//form[@method=\"GET\"][@class='formy']"))
----
* find a button by its text (exact match):
+
[source,clojure]
----
(= (e/query driver {:tag :button :fn/text "Submit Form"})
;; equivalent in xpath:
(e/query driver ".//button[text() = 'Submit Form']"))
----
* find an nth element (`p`, `div`, whatever, it does not matter) with "blarg" text:
+
[source,clojure]
----
(e/get-element-text driver {:fn/has-text "blarg" :index 3})
;; => "blarg in a p"
;; equivalent in xpath:
(e/get-element-text driver ".//*[contains(text(), 'blarg')][3]")
;; => "blarg in a p"
----
* find an element that includes a class:
+
[source,clojure]
----
(e/get-element-text driver {:tag :span :fn/has-class "class1"})
;; => "blarg in a span"
;; equivalent xpath:
(e/get-element-text driver ".//span[contains(@class, 'class1')]")
;; => "blarg in a span"
----
* find an element that has the following domain in a `href`:
+
[source,clojure]
----
(e/get-element-text driver {:tag :a :fn/link "clojure.org"})
;; => "link 3 (clojure.org)"
;; equivalent xpath:
(e/get-element-text driver ".//a[contains(@href, \"clojure.org\")]")
;; => "link 3 (clojure.org)"
----
* find an element that includes all of the specified classes:
+
[source,clojure]
----
(e/get-element-text driver {:fn/has-classes [:class2 :class3 :class5]})
;; => "blarg in a div"
;; equivalent in xpath:
(e/get-element-text driver ".//*[contains(@class, 'class2')][contains(@class, 'class3')][contains(@class, 'class5')]")
;; => "blarg in a div"
----
* find explicitly enabled/disabled input widgets:
+
[source,clojure]
----
;; first enabled input
(= (e/query driver {:tag :input :fn/enabled true})
;; equivalent xpath:
(e/query driver ".//input[@enabled=true()]"))
;; => true
;; first disabled input
(= (e/query driver {:tag :input :fn/disabled true})
;; equivalent xpath:
(e/query driver ".//input[@disabled=true()]"))
;; => true
;; return a vector of all disabled inputs
(= (e/query-all driver {:tag :input :fn/disabled true})
;; equivalent xpath:
(e/query-all driver ".//input[@disabled=true()]"))
;; => true
----
=== Vector Syntax Queries
A query can be a vector of any valid query expressions.
For vector queries, every expression matches the output from the previous expression.
A simple, somewhat contrived, example:
[source,clojure]
----
(e/click driver [{:tag :html} {:tag :body} {:tag :button}])
;; our sample page shows form submits, did it work?
(e/get-element-text driver :submit-count)
;; => "1"
----
You may combine both XPath and CSS expressions
TIP: Reminder: the leading dot in an XPath expression means starting at the current node
[source,clojure]
----
;; under the html tag (using map query syntax),
;; under a div tag with a class that includes some-links (using css query),
;; click on a tag that has
;; a class attribute equal to active (using xpath syntax):
(e/click driver [{:tag :html} {:css "div.some-links"} ".//a[@class='active']"])
;; our sample page shows link clicks, did it work?
(e/get-element-text driver :clicked)
;; => "link 2 (active)"
----
=== Advanced Queries
==== Querying the _nth_ Element Matched
Sometimes you may want to interact with the _nth_ element of a query.
Maybe you want to click on the second link within:
[source,html]
----
<ul>
<li class="search-result">
<a href="a">a</a>
</li>
<li class="search-result">
<a href="b">b</a>
</li>
<li class="search-result">
<a href="c">c</a>
</li>
</ul>
----
You can use the `:index` like so:
[source,clojure]
----
(e/click driver [{:tag :li :class :search-result :index 2} {:tag :a}])
;; check click tracker from our sample page:
(e/get-element-text driver :clicked)
;; => "b"
----
:nth-child: https://www.w3schools.com/CSSref/sel_nth-child.asp
or you can use the link:{nth-child}[nth-child trick] with the CSS expression like this:
[source,clojure]
----
;; start page anew
(e/refresh driver)
(e/click driver {:css "li.search-result:nth-child(2) a"})
(e/get-element-text driver :clicked)
;; => "b"
----
Finally it is also possible to obtain the _nth_ element directly by using `query-all`:
[source,clojure]
----
;; start page anew
(e/refresh driver)
(e/click-el driver (nth (e/query-all driver {:css "li.search-result a"}) 1))
(e/get-element-text driver :clicked)
;; => "b"
----
[NOTE]
====
Notice:
* The use of `click-el` here. The `query-all` function returns an element, not a selector that can be passed to `click` directly
* The nth offset of 1 instead of 2. Clojure's nth is 0-based, and our search indexes are 1-based.
====
==== Querying a Tree [[query-tree]]
`query-tree` pipes selectors.
Every selector queries elements from the previous one.
The first selector finds elements from the root, subsquent selectors find elements downward from each of the previous found elements.
Given the following HTML:
[source,html]
----
<div id="query-tree-example">
<div id="one">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
</div>
<div id="two">
<a href="#">a4</a>
<a href="#">a5</a>
<a href="#">a6</a>
</div>
<div id="three">
<a href="#">a7</a>
<a href="#">a8</a>
<a href="#">a9</a>
</div>
</div>
----
The following query will find a vector of `div` tags, then return a set of all `a` tags under those `div` tags:
[source,clojure]
----
(->> (e/query-tree driver :query-tree-example {:tag :div} {:tag :a})
(map #(e/get-element-text-el driver %))
sort)
;; => ("a1" "a2" "a3" "a4" "a5" "a6" "a7" "a8" "a9")
----
=== Interacting with Queried Elements
To interact with elements found via a `query` or `query-all` function call you have to pass the query result to either `click-el` or `fill-el` (note the `-el` suffix):
[source,clojure]
----
(e/click-el driver (first (e/query-all driver {:tag :a})))
----
You can collect elements into a vector and arbitrarily interact with them at any time:
[source,clojure]
----
(e/refresh driver)
(def elements (e/query-all driver {:tag :input :type :text :fn/disabled false}))
(e/fill-el driver (first elements) "This is a test")
(e/fill-el driver (rand-nth elements) "I like tests!")
----
== Interactions
Some basic interactions are covered under <<querying>>, here we go into other types of interactions and more detail.
=== Emulate how a Real Person Might Type
Real people type slowly and make mistakes.
To emulate these characteristics, you can use the `fill-human` function.
The following options are enabled by default:
[source,clojure]
----
{:mistake-prob 0.1 ;; a real number from 0.1 to 0.9, the higher the number, the more typos will be made
:pause-max 0.2} ;; max typing delay in seconds
----
which you can choose to override if you wish:
[source,clojure]
----
(e/refresh driver)
(e/fill-human driver :uname "soslowsobad"
{:mistake-prob 0.5
:pause-max 1})
;; or just use default options by omitting them
(e/fill-human driver :uname " typing human defaults")
----
For multiple inputs, use `fill-human-multi`
[source,clojure]
----
(e/refresh driver)
(e/fill-human-multi driver {:uname "login"
:pw "password"
:text "some text"}
{:mistake-prob 0.1
:pause-max 0.1})
----
=== Mouse Clicks
The `click` function triggers the left mouse click on an element found by a query term:
[source,clojure]
----
(e/click driver {:tag :button})
----
The `click` function uses only the first element found by the query, which sometimes leads to clicking on the wrong items.
To ensure there is one and only one element found, use the `click-single` function.
It acts the same but raises an exception when querying the page returns multiple elements:
[source,clojure]
----
(e/click-single driver {:tag :button :name "submit"})
----
Although double-clicking is rarely purposefully employed on web sites, some naive users might think it is the correct way to click on a button or link.
A double-click can be simulated with `double-click` function (Chrome, Phantom.js).
It can be used, for example, to check your handling of disallowing multiple form submissions.
[source,clojure]
----
(e/double-click driver {:tag :button :name "submit"})
----
There are also "blind" clicking functions.
They trigger mouse clicks on the current mouse position:
[source,clojure]
----
(e/left-click driver)
(e/middle-click driver)
(e/right-click driver)
----
Another set of functions do the same but move the mouse pointer to a specified element before clicking on them:
[source,clojure]
----
(e/left-click-on driver {:tag :a})
(e/middle-click-on driver {:tag :a})
(e/right-click-on driver {:tag :a})
----
A middle mouse click can open a link in a new background tab.
The right click sometimes is used to imitate a context menu in web applications.
=== Selecting an option from a dropdown [[select-dropdown]]
An `<option>` from a `<select>` can be selected via the `click` function.
Given the following HTML:
[source,html]
----
<select id="dropdown" name="options">
<option value="o1">foo one</option>
<option value="o2">bar two</option>
<option value="o3">bar three</option>
<option value="o4">bar four</option>
</select>
----
Click on option with value `o4`:
[source,clojure]
----
(e/click driver [{:id :dropdown} {:value "o4"}])
(e/get-element-value driver :dropdown)
;; => "o4"
----
Click on option with text `bar three`:
[source,clojure]
----
(e/click driver [{:id :dropdown} {:fn/text "bar three"}])
(e/get-element-value driver :dropdown)
;; => "o3"
----
TIP: Safari Quirk: You might need to first click on the `select` element, then the option.
[NOTE]
====
Etaoin also includes the https://cljdoc.org/d/etaoin/etaoin/CURRENT/api/etaoin.api#select[select] convenience function. It will select the first option from a dropdown that includes the specified text. It also automatically handles the Safari quirk.
Click first matching option with text `bar`:
[source,clojure]
----
(e/select driver :dropdown "bar")
(e/get-element-value driver :dropdown)
;; => "o2"
----
The same operation expressed with `click`:
[source,clojure]
----
(e/click driver :dropdown) ;; needed for Safari quirk only
(e/click driver [{:id :dropdown} {:fn/has-text "bar"}])
(e/get-element-value driver :dropdown)
;; => "o2"
----
====
=== Keyboard Chords
There is an option to input a series of keys simultaneously.
This useful to imitate holding a system key like Control, Shift or whatever when typing.
The namespace `etaoin.keys` includes key constants as well as a set of functions related to keyboard input.
[source,clojure]
----
(require '[etaoin.keys :as k])
----
A quick example of entering ordinary characters while holding Shift:
[source,clojure]
----
(e/refresh driver)