【问题标题】:How can I execute a Javascript function from VBScript?如何从 VBScript 执行 Javascript 函数?
【发布时间】:2011-01-13 07:03:53
【问题描述】:

我正在尝试使用 WSH 脚本从网页下载 Excel 文件

我的目标是将网页中的 Excel 文件保存到我的机器上。

到目前为止,我采取的步骤是:制作了一个 vbs 文件,该文件登录到 https 网页,使用打开一个新选项卡的第二个运行命令将我重定向到另一个页面,但在那之后我的知识有限'无法找到有关如何从网站上的下载链接将文件下载到我的硬盘驱动器上的位置的解决方案。

Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
WshShell.Run "URL", 9
wscript.sleep 3000
WshShell.SendKeys "username@"
WshShell.SendKeys "{tab}"
WshShell.SendKeys "password"
WshShell.SendKeys "{enter}"
WshShell.Run "Another_URL"

现在有一个下载链接,它有一个javascript函数javascript:download(parameters),手动点击它会生成一个唯一的下载链接。

有什么方法可以使用任何 Wscript 下载它吗?我希望它与 Windows 7 和 IE 7 一起工作。我已经尝试过研究它,但它无济于事。

【问题讨论】:

    标签: windows internet-explorer vbscript wsh


    【解决方案1】:

    我使用类似于此的脚本取得了一些成功

    option explicit
    
    Const URL = "http://url/to/file.xls"
    Const adTypeBinary = 1
    Const adSaveCreateOverWrite = 2
    
    ' request the file over http
    dim http: set http = CreateObject("MSXML2.XMLHTTP")
    http.open "GET", URL, false
    http.send
    
    ' write the response text to a binary file
    dim stream: set stream = CreateObject("ADODB.Stream")
    stream.type = adTypeBinary 
    stream.open
    stream.write http.responseBody
    stream.SaveToFile "output.xls", adSaveCreateOverWrite 
    stream.close
    

    虽然我没有将它用于 https 请求,但我假设服务器将接受您的用户名和密码作为 MSXML2.XMLHTTPopen 调用的第 4 和第 5 个参数。

    http.open "GET", URL, false, "username@", "password"
    

    我已经尝试过了,它确实可以在普通的 http 请求上运行

    http 请求见http://msdn.microsoft.com/en-us/library/ms759148(VS.85).aspx,adodb 流见http://msdn.microsoft.com/en-us/library/ms675032(VS.85).aspx


    以上方法的替代方法是使用 Internet Explorer 自动化对象。我不确定你如何处理文件下载,但下面的 sn-p 可能会给你一个起点

    option explicit
    
    ' create an instance of IE
    dim ie: set ie = CreateObject("InternetExplorer.Application")
    ' load a url
    ie.Navigate "http://*.com/questions/4677595/how-can-i-execute-a-javascript-function-from-vbscript"
    ' sleep while IE loads the content
    do while ie.busy
        WScript.Sleep 10
    loop
    'access the document object
    dim doc: set doc = ie.document
    
    ' have IE natvigate to a link on the downloaded page. this could be your
    ' download link perhaps?
    ie.Navigate doc.anchors(0).href 
    ' wait while the new page loads...
    do while ie.busy
        WScript.Sleep 10
    loop
    ' output the new content
    WScript.Echo doc.documentElement.innerHTML
    ' close IE
    ie.Quit
    

    【讨论】:

    • 这是生成的链接Fixed_URL/Random_No_Generated?_tbldnld=(1stparam)&sc=(fn 的第二个参数) 手动会发生这种情况,点击下载后会打开一个文件下载框,然后我点击保存将其保存到某个位置。 URL 没有文件名,但名称与随机编号相同。那么,我能否以编程方式模仿这种行为,如果可以,是否可以使用脚本或必须编写任何程序 - 请指导我,如果不是,为什么不可能。谢谢 oracle 认证的专家的帮助,但我不知道如何解决这个问题.