首页 > 解决方案 > 无法在 IE 中执行 javascript

问题描述

我使用 IE 在 vba 中创建了一个脚本来单击网页中的选项卡。我想知道如何使用.execScript.

当我像下面这样尝试时,它可以工作(不是理想的方法):

Sub ExecuteScript()
    Dim IE As New InternetExplorer, Html As HTMLDocument

    With IE
        .Visible = True
        .navigate "https://stackoverflow.com/questions/tagged/web-scraping"
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document
        Html.parentWindow.execScript "document.querySelector(""a[href='/questions/ask']"").click();"
    End With
End Sub

我想做的方式如下,以便我可以使用对象变量(相邻或内部).execScript

Set post = Html.querySelector("a[href='/questions/ask']")
Html.parentWindow.execScript "arguments[0].click();", post

但是,它会引发指向此行的错误Html.parentWindow.execScript

Run-time error `429`
ActiveX component can't create object

如何在 IE 中执行 javascript?

标签: vbaweb-scrapinginternet-explorer-11

解决方案


为什么不更改变量类型以便可以post作为字符串传递(即选择器)。然后你可以连接进来。

Option Explicit
Public Sub ExecuteAScript()
    Dim IE As New InternetExplorer, Html As HTMLDocument, post As String, item As Object
    post = "a[href='/questions/ask']"

    With IE
        .Visible = True
        .navigate "https://stackoverflow.com/questions/tagged/web-scraping"
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document
        Do
            On Error Resume Next
            Set item = .document.querySelector("" & post & "")
            On Error GoTo 0
        Loop While item Is Nothing

        If Not item Is Nothing Then item.Click

        Stop
    End With
End Sub

如果您必须使用execScript,我认为您不能return像使用 selenium 那样使用 javascript 调用传回值。您可以使用 js 向页面添加一个值,然后将其读回以返回:

Option Explicit
Public Sub ExecuteAScript()
    Dim IE As New InternetExplorer
    post = "a[href='/questions/ask']"

    With IE
        .Visible = True
        .navigate "https://stackoverflow.com/questions/tagged/web-scraping"
        While .Busy Or .readyState < 4: DoEvents: Wend
        Do
            Call .document.parentWindow.execScript("document.title = document.querySelectorAll(" & Chr$(34) & post & Chr$(34) & ").length;")
        Loop While .document.Title = 0
        If IsNumeric(.document.Title) And .document.Title > 0 Then Debug.Print "Success"
    End With
End Sub

推荐阅读