Utilizzo del codice java-script in Mathematica

Sep 04 2020

Ho il seguente file HTML memorizzato in "C: \ local.html":

<html>
<head>
<script type="text/javascript">

function execute()
{
    const urlParams = new URLSearchParams(window.location.search);
    const param = urlParams.get('param');
    var text_box = document.getElementById("path_text");
    text_box.value = param;
}

</script>

</head>
<body onload="execute()">

<textarea id="path_text" rows="40" cols="80" style="font-size:75%"></textarea><br/>

</body>
</html>

Se apro il file nel mio browser web come "file: /// C: /local.html? Param = Qualche testo interessante" Ho una pagina web con l'area di testo che contiene il testo "Testo interessante" a cui è stato passato la variabile java-script tramite URL param.

Ora voglio importare lo stesso file in Mathematica con lo stesso parametro URL e quindi estrarre il contenuto di textarea id="path_text"dopo che lo script java è stato eseguito.

Il codice seguente

Import["file:///C:/local.html?param=some dfsf"]

restituisce l'errore "File non trovato".

I due codici seguenti non danno errori ma non forniscono dati, come il codice java-script non è stato eseguito o / e il parametro URL non è stato passato.

Import["file:///C:/local.html", 
 Parameters -> {"param" -> "Some interesting text"}]

Import["C:\\local.html", 
 Parameters -> {"param" -> "Some interesting text"}]

Come importare file HTML locali con parametri URL passati a java-script e java-script eseguiti?

AGGIORNARE:

Usando il consiglio di flinty da usare StartWebSessione WebExecuteho capito come estrarre il contenuto dall'area di testo tramite codice java-script:

session = StartWebSession[Visible -> False];
WebExecute[
  "OpenPage" -> "file:///C:/local.html?param=Some interesting text"];
WebExecute[session, 
 "JavascriptExecute" -> 
  "return document.getElementById('path_text').value"]
DeleteObject[session]
Clear[session]

(*"Some interesting text"*)

Risposte

3 flinty Sep 04 2020 at 16:07

Posso caricare la pagina con Firefox e ottenere l'elemento. Ma non credo che Wolfram abbia implementato l'estrazione degli attributi tramite XPath. Usare le "JavascriptExecute"opere comunque.

session = StartWebSession[Visible -> False];
WebExecute[session, {
  "OpenPage" -> "file:///C:/local.html?param=some%20dfsf"
}]

(* here we try to get the element and it works *)
e = WebExecute[session, {
  "LocateElements" -> "XPath" -> "//*[@id='path_text']"
}]

(* here we try to get the .value attribute, but it won't work and returns {{}}.
 This XPath query doesn't even work in the Firefox console either. *)
a = WebExecute[session, {
  "LocateElements" -> "XPath" -> "//*[@id='path_text']/@value"
}]

(* we can try to execute js on the page to extract the attribute, this works *)
result = WebExecute[session, 
  "JavascriptExecute" -> "return document.getElementById('path_text').value"]

DeleteObject[session]