vba - 无法在 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?
解决方案
为什么不更改变量类型以便可以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
推荐阅读
- c - 为什么 C 中 malloc 的类型转换在右边而不是左边有 * 符号?
- swift - 从 Swift 中另一个字符串的引用字符中获取字符
- c - 在整数序列中查找距离 D 范围内有多少对数字
- node.js - 无法在 Node.js 中导入 firebase-admin
- mysql - 如何选择具有最新日期的行并根据该行计算另一个字段
- python - 选择一个有效的选项。...不是可用的选择之一
- javascript - 函数后删除范围
- r - 将自定义函数传递给 RMarkdown YAML df_print 以在编织 HTML 输出时打印数据帧
- java - 请求的资源 [projectname/servlet] 不可用
- java - JavaFX 将 null 返回给列出的用户