My end goal is to dynamically get music playing. I figured that navigating to youtube, searching for the string, and playing the first video suggested is a good way of getting this done. Pandora and Spotify both have hoops that you need to jump through before playing.
Sub YouTube()
So we open up IE, and navigate to the website
Set objIE = CreateObject("InternetExplorer.Application")
WebSite = "www.youtube.com"
With objIE
.Visible = True
.navigate WebSite
Do While .Busy Or .readyState <> 4
DoEvents
Loop
So far, so good. Next we find the search box, and make a search. Dummy text entered for the sake of easy coding, it'll eventually be an argument passed to the function.
Set Element = .document.getelementsbyname("search_query")
Element.Item(0).Value = "portal 2 walkthrough video"
.document.forms(1).submit
Do While .Busy Or .readyState <> 4
DoEvents
Loop
Great, we made it! Now for the part I'm struggling on - clicking on the first video.
I've tried a few different things - I can't seem to find a name, and I keep getting a "Permission denied" when I try to do something like this, as suggested by other users. See: How do I click a link on a web page using Excel VBA?
I've decided not to programatically control the mouse and click, since the location I need to click on keeps dynamically changing.
I'm not very good at interfacing with IE while using VBA, so at this point I'm stumped.
Set Element2 = .document.getelementsbytagname("a")
For Each i In Element2
If i.classname = "yt-lockup-content" Then
i.Click
Exit For
Else
'do nothing
End If
Next i
End With
End Sub
I've also tried:
.document.getelementsbyclassname("yt-lockup-content").Click
But that's not a supported method
.document.querySelector("a[href=javascript:browserPrint();]").Click
Gets a permission denied