การใช้รหัส java-script ใน Mathematica

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 = ข้อความที่น่าสนใจ" ฉันได้รับหน้าเว็บที่มีพื้นที่ข้อความที่มีข้อความ "ข้อความที่น่าสนใจ" ที่ส่งไปยัง paramจาวาสคริปต์โดยตัวแปร

ตอนนี้ฉันต้องการนำเข้าไฟล์เดียวกันไปยัง Mathematica ด้วยพารามิเตอร์ URL เดียวกันจากนั้นแยกเนื้อหาtextarea id="path_text"หลังจากเรียกใช้สคริปต์ java

รหัสต่อไปนี้

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

ให้ข้อผิดพลาด "ไม่พบไฟล์"

รหัสสองรหัสต่อไปนี้ไม่มีข้อผิดพลาด แต่ยังไม่ให้ข้อมูลเช่นรหัส java-script ไม่ได้ถูกเรียกใช้งานหรือ / และไม่ได้ส่งผ่านพารามิเตอร์ URL

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

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

วิธีการนำเข้าไฟล์ HTML ภายในที่มีพารามิเตอร์ URL ที่ส่งผ่านไปยัง java-script และ java-script ที่เรียกใช้งาน

อัพเดท:

ใช้คำแนะนำในการใช้ของ flinty StartWebSessionและWebExecuteฉันได้หาวิธีแยกเนื้อหาจากพื้นที่ข้อความด้วยรหัส 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"*)

คำตอบ

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]