Mathematicaでjava-scriptコードを使う

Sep 04 2020

次のHTMLファイルを「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>

「file:/// C:/local.html?param = Someinterestedtext」のようにWebブラウザでファイルを開くと、渡された「Someinterestingtext」というテキストを含むテキスト領域のあるWebページが表示されます。 URL変数によるjava-script param。

ここで、同じURLパラメータを使用して同じファイルをMathematicaにインポートしtextarea id="path_text"、Javaスクリプトが実行された後のコンテンツを抽出したいと思います。

次のコード

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

「ファイルが見つかりませんでした」というエラーが表示されます。

次の2つのコードはエラーを発生させませんが、java-scriptコードが実行されなかった、またはURLパラメーターが渡されなかったなどのデータも提供しません。

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

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

渡されたURLパラメータを含むローカルHTMLファイルをjava-scriptにインポートしてjava-scriptを実行するにはどうすればよいですか?

更新:

flintyのアドバイスを使用してStartWebSession、WebExecutejava-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"*)

回答

3 flinty Sep 04 2020 at 16:07

Firefoxでページを読み込んで、要素を取得できます。しかし、WolframがXPathを介した属性の抽出を実装しているとは思いません。"JavascriptExecute"ただし、使用は機能します。

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]