From aa90607cc75c4f81cc8da57188567680c2907acf Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 13 May 2023 20:31:46 +0200 Subject: [PATCH] find element with XPath --- bin/twitter.ml | 12 ++++++++++-- lib/json.ml | 9 +++++++++ lib/net.ml | 23 ++++++++++++++++++++++- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/bin/twitter.ml b/bin/twitter.ml index f4023e5..d88158d 100644 --- a/bin/twitter.ml +++ b/bin/twitter.ml @@ -3,7 +3,15 @@ open Pusk.Utils let login_twitter ctx _username _password = (* Navigate to login page *) - ignore (navigate "https://twitter.com/i/flow/login" ctx.session_id); + ignore (navigate ctx.session_id "https://twitter.com/i/flow/login"); (* Extra wait to be sure the page is loaded *) - Unix.sleep 5 + Unix.sleep 5; + match + find + ctx.session_id + (XPath + "/html/body/div[1]/div/div/div[1]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[5]/label") + with + | Some l -> List.iter (fun e -> print_endline (Yojson.Safe.to_string e)) l + | None -> raise (Any "Username input not found") ;; diff --git a/lib/json.ml b/lib/json.ml index 6dc7304..e3c6f4e 100644 --- a/lib/json.ml +++ b/lib/json.ml @@ -26,3 +26,12 @@ let execute_payload src = fmt {| "args": [] } |} src + +let find_payload strategy value = + fmt {| + { + "using": "%s", + "value": "%s" + } + |} strategy value +;; diff --git a/lib/net.ml b/lib/net.ml index e5082b8..5d49ec2 100644 --- a/lib/net.ml +++ b/lib/net.ml @@ -51,6 +51,12 @@ let execute_sync session_id src = (Json.execute_payload src) ;; +type strategy = XPath of string + +let get_strategy = function + | XPath xpath -> "xpath", xpath +;; + let rec wait_for_load session_id = let response = execute_sync session_id "return document.readyState" in match Yojson.Safe.from_string response with @@ -65,7 +71,7 @@ let rec wait_for_load session_id = | _ -> raise (Any "wait_for_load | Invalid JSON") ;; -let navigate ?(wait = true) url session_id = +let navigate ?(wait = true) session_id url = let res = execute_post_request (fmt "%s/url" (driver session_id)) (Json.navigate_payload url) in @@ -74,3 +80,18 @@ let navigate ?(wait = true) url session_id = ;; let screenshot session_id = execute_get_request (fmt "%s/screenshot" (driver session_id)) + +let find session_id strategy = + let engine, search = get_strategy strategy in + let response = + execute_post_request + (fmt "%s/elements" (driver session_id)) + (Json.find_payload engine search) + in + match Yojson.Safe.from_string response with + | `Assoc fields -> + (match List.assoc "value" fields with + | `List l -> Some l + | _ -> None) + | _ -> raise (Any "wait_for_load | Invalid JSON") +;;