注意:几天前我在VBA Express上发布了同样的问题但是无法解决这个问题。不想做任何双重工作。
我正在尝试访问某个网站并使用onclick参考播放声音。我每次使用我的代码都无法播放声音。它会每隔几次播放,虽然这对我来说很奇怪。我不能使用getelementbyid,因为我打算搜索几个链接并且事先不知道id是什么。关于如何每次都能播放声音的任何想法?谢谢。
Sub Encore()
Dim oBrowser As InternetExplorer
Dim sURL As String
sURL = "http://forvo.com"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.navigate sURL
oBrowser.Visible = True
Do While oBrowser.Busy: DoEvents: Loop
oBrowser.navigate "http://forvo.com/search/encore/fr"
Do While oBrowser.Busy: DoEvents: Loop
oBrowser.document.getElementsByClassName("play")(0).Click
End sub
另一次尝试:
Sub Encore()
Dim oBrowser As InternetExplorer
Dim div As HTMLDivElement
Dim sURL As String
sURL = "http://forvo.com"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.navigate sURL
oBrowser.Visible = True
Do While oBrowser.Busy: DoEvents: Loop
oBrowser.navigate "http://forvo.com/search/encore/fr"
Do While oBrowser.Busy: DoEvents: Loop
Set div = oBrowser.document.getElementsByClassName("play")(0)
div.FireEvent "onclick"
End sub
答案 0 :(得分:0)
我按标签名称“a”获取元素并执行循环语句,直到元素名称找到,如果找到名称并单击链接。
您在for循环中使用任何名称的link元素
Sub Encore()
Dim oBrowser As InternetExplorer
Dim mydoc As HTMLDocument
Dim sURL As String
sURL = "http://forvo.com"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.navigate sURL
oBrowser.Visible = True
Do While oBrowser.Busy: DoEvents: Loop
oBrowser.navigate "http://forvo.com/search/encore/fr"
Do While oBrowser.Busy: DoEvents: Loop
Set mydoc = oBrowser.document
Set div = mydoc.getElementsByTagName("a")
For Each link In div
Debug.Print link.Text
If link.Text = "encore" Then
link.Click
Exit For
End If
Next link
Set div = mydoc.getElementsByTagName("a")
For Each link In div
Debug.Print link.Text
If link.Text = "encore pronunciation" Then
link.Click
Application.Wait DateAdd("s", 1, Now)
link.Click
Exit For
End If
Next link
End Sub
答案 1 :(得分:0)
谢谢Kathir的帮助。我找到了解决问题的方法。它可能不是最干净的解决方案,但它确实有效。班级名称将改变为" play"到#34;播放加载"点击后。有时声音会发挥作用,但是当它没有出现类名时,就会发挥加载效果。所以我只是设置一个For循环来检查"播放加载"类名,如果它不存在则退出循环。
Sub Encore()
Dim oBrowser As InternetExplorer
Dim sURL As String
Dim a As Integer
sURL = "http://forvo.com"
On Error Resume Next
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.navigate sURL
oBrowser.Visible = True
Do While oBrowser.Busy: DoEvents: Loop
oBrowser.navigate "http://forvo.com/search/encore/fr"
Do While oBrowser.Busy: DoEvents: Loop
For a = 0 To 50
oBrowser.document.getElementsByClassName("play")(0).Click
Application.Wait Now + TimeValue("00:00:01")
If oBrowser.document.getElementsByClassName("play loading")(0).innerText = "" Then
Exit For
End If
Next a
a = 0
End Sub