我在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?
为什么不更改变量类型,以便可以将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
我不认为你可以使用javascript return
调用传递值,因为你可以使用selenium。您可以使用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