Skip to content

Commit 542bdec

Browse files
Ankush KalkoteAnkush Kalkote
Ankush Kalkote
authored and
Ankush Kalkote
committed
Practice Selenium Json protocol
0 parents  commit 542bdec

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

element.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"using": "name",
3+
"value": "q"
4+
}

selenium-wire.rb

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
require "json"
2+
require "base64"
3+
4+
selenium_server = "http://127.0.0.1:4444/wd/hub"
5+
6+
def parseRespAndCheckStatus(resp, operation)
7+
parsed_resp = JSON.parse(resp)
8+
status = parsed_resp["status"]
9+
raise StandardError "#{operation} failed with error-code #{status}" unless status==0
10+
return parsed_resp
11+
end
12+
13+
# Create a session
14+
url = selenium_server + "/session"
15+
resp = `curl -X POST -d @browser-caps.json #{url}`
16+
parsed_resp = parseRespAndCheckStatus(resp, "Creating session")
17+
session_id = parsed_resp["sessionId"]
18+
puts "Session id is #{parsed_resp["sessionId"]}"
19+
20+
# Open a url in the browser
21+
url = selenium_server + "/session/#{session_id}/url"
22+
resp = `curl -X POST -d @url.json #{url}`
23+
parseRespAndCheckStatus(resp, "Opening url")
24+
25+
# Find the search box element
26+
url = selenium_server + "/session/#{session_id}/element"
27+
resp = `curl -X POST -d @element.json #{url}`
28+
parsed_resp = parseRespAndCheckStatus(resp, "Searching element")
29+
webelement = parsed_resp["value"]["ELEMENT"]
30+
puts "webelement json is #{webelement}"
31+
32+
# Send keystrokes to the element
33+
url = selenium_server + "/session/#{session_id}/element/#{webelement}/value"
34+
resp = `curl -X POST -d "{"value":["Browserstack"]}" #{url}`
35+
parseRespAndCheckStatus(resp, "Sending keystrokes")
36+
37+
# wait for loading
38+
sleep 3
39+
40+
# Get the title of current page
41+
url = selenium_server + "/session/#{session_id}/title"
42+
resp = `curl #{url}`
43+
parsed_resp = parseRespAndCheckStatus(resp, "Getting title")
44+
puts "The title of the window is #{parsed_resp["value"]}"
45+
46+
# Take a screenshot
47+
url = selenium_server + "/session/#{session_id}/screenshot"
48+
resp = `curl #{url}`
49+
parsed_resp = parseRespAndCheckStatus(resp, "Taking screenshot")
50+
image = Base64.decode64(parsed_resp["value"])
51+
File.open('screenshot.png', 'wb') { |f| f.write(image) }
52+
53+
# Delete the session
54+
url = selenium_server + "/session/#{session_id}"
55+
resp = `curl -X DELETE #{url}`
56+
parseRespAndCheckStatus(resp, "Closing the session")

url.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"url":"http://www.google.com"
3+
}

0 commit comments

Comments
 (0)