【问题标题】:Trouble executing javascript within IE无法在 IE 中执行 javascript
【发布时间】:2019-07-31 05:32:46
【问题描述】:

我在 vba 中创建了一个脚本,使用 IE 单击网页中的选项卡。我想知道如何使用.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?

【问题讨论】:

    标签: vba web-scraping internet-explorer-11


    【解决方案1】:

    为什么不更改变量类型,以便您可以将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,我认为您不能像使用selenium 那样使用javascript return 调用传回值。您可以使用 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
    

    【讨论】:

    • 是的,我一开始就想到了,但问题是我无法创建任何do loop 或类似Do: Set post = Html.querySelector("a[href='/questions/ask']"): DoEvents: Loop While post Is Nothing 的东西来检查是否存在任何元素,然后再使用它Html.parentWindow.execScript 线。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2012-07-02
    • 2014-04-21
    相关资源
    最近更新 更多