Usando código java-script en Mathematica

Sep 04 2020

Tengo el siguiente archivo HTML almacenado en "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>

Si abro el archivo en mi navegador web como "file: /// C: /local.html? Param = Algún texto interesante", obtengo una página web con el área de texto que contiene el texto "Algún texto interesante" que se pasó a el script java por variable de URL param.

Ahora quiero importar el mismo archivo a Mathematica con el mismo parámetro de URL y luego extraer el contenido de textarea id="path_text"después de que se ejecutó el script java.

El siguiente código

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

da el error "Archivo no encontrado".

Los siguientes dos códigos no dan ningún error, pero tampoco dan datos, como el código java-script no se ejecutó o / y no se pasó el parámetro URL.

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

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

¿Cómo importar un archivo HTML local con parámetros de URL pasados ​​a java-script y java-script ejecutados?

ACTUALIZAR:

Usando el consejo de flinty para usar StartWebSessiony WebExecutedescubrí cómo extraer el contenido del área de texto mediante el código de script java:

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"*)

Respuestas

3 flinty Sep 04 2020 at 16:07

Puedo cargar la página con Firefox y obtener el elemento. Pero no creo que Wolfram haya implementado la extracción de atributos a través de XPath. "JavascriptExecute"Sin embargo, el uso funciona.

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]