在这里,我试图使用一个实例来复制我在安全网络中面临的一个问题,以便有人可以帮我找到解决方案。
事实上,我为同一个问题打开了一个问题(VBA: How to click a drop down in a web page with the help of HREF and CLASS HTML tag avilable),但我还是找不到解决方案。
预期结果: 帮助我打开网页(https://www.amazon.in/)并使用HTML标记CLASS和HREF从菜单栏导航到下拉列表(Today's Deal)的代码。 [示例(网站)在这里给出了“tabindex”,但请不要使用它作为解决方案,因为在我的真实场景中除了href&之外我没有任何其他标签。 class(请找到我为真实网页制作的HTML标签的屏幕截图)]
VBA代码
Sub Click_aLinkorDropdown()
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
'On Error GoTo Err_Clear
MyURL = "https://www.amazon.in/"
Set MyBrowser = New InternetExplorerMedium
MyBrowser.Silent = True
MyBrowser.navigate MyURL
MyBrowser.Visible = True
For Each MyHTML_Element In HTMLDoc.getElementsByClassName("nav-a")
If InStr(MyHTML_Element.href, "/gp/goldbox/ref=nav_cs_gb") Then
MyHTML_Element.Click
Exit For
Next
'Err_Clear:
'If Err <> 0 Then
'Err.Clear
'Resume Next
'End If
End Sub
HTML TAG
href='/gp/goldbox/ref=nav_cs_gb' class='nav-a' tabindex='22'>Today's Deals</a><a
使用此代码我面临的问题 网页打开,当它到达时点击链接我得到两种类型的错误1:&gt;运行时错误438:对象不支持此属性或方法
2:&gt;运行时错误424:需要对象
我还尝试了StackOverflow中的一个帖子,但this is not working for me
答案 0 :(得分:1)
使用以下代码并记住启用引用Microsoft Internet Controls
和Microsoft HTML Object Library
:
#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
Sub test()
Dim IE As Object
Dim HTMLDoc As Object
Dim sURL As String
' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")
sURL = "https://www.amazon.in/"
' WEBPAGE NAVIGATION
With IE
.Navigate (sURL)
.Visible = True
End With
WaitIE IE, 2000
' CLICK ON LOG IN
Set HTMLDoc = IE.Document
Set buttonclick = HTMLDoc.getElementsByClassName("nav-a")
For Each Element In buttonclick
If Element.href = "https://www.amazon.in/gp/goldbox/ref=nav_cs_gb" Then Element.Click
Next Element
WaitIE IE, 5000
'IE.Quit
'Set IE = Nothing
End Sub
Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
Sleep time
Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.READYSTATE = 4) & _
vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
i = i + 1
Loop Until IE.READYSTATE = 4 Or Not IE.Busy
End Sub
您可以参考this answer获取类似的答案代码。