• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Trouble using querySelector in vba

shahin

Active Member
I've written some code using vba to get all the movie names from a specific webpage out of a torrent site. However, pressing "F8" I could find out that the code works well and prints the results until it hits the last result from that page. As soon as it reaches the last name to parse, the program crashes. I did several times and suffered the same consequences. If vba doesn't support this css selector method then how could I collect results before the last one? Is there any reference to add in the library or something else before execution? It would be awesome if it is possible to scrape webpages using css selector. Any help on this will be vastly appreciated. here is the code I have written:

Code:
Sub Torrent_data()
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim movie_name As Object
  
    With http
        .Open "GET", "https://www.yify-torrent.org/search/1080p/", False
        .send
        html.body.innerHTML = .responseText
    End With
  
    For Each movie_name In html.querySelectorAll("div.mv h3 a")
        x = x + 1
        Cells(x, 1) = movie_name.innerText
    Next movie_name
End Sub
 
But, if I go like this, it works. Now, I find it even more confusing. Could anybody tell me, why querySelectorAll behaves like this and how can I control it?
Code:
Sub Torrent_data()

    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim movie_name As Object

    With http
        .Open "GET", "https://www.yify-torrent.org/search/1080p/", False
        .send
        html.body.innerHTML = .responseText
    End With

    Set movie_name = html.querySelectorAll("div.mv h3 a")

    For i = 0 To movie_name.Length - 1
        x = x + 1: Cells(x, 1) = movie_name(i).innerText
    Next i

End Sub
 
querySelectorAll... returns NodeList object.

Which is collection of nodes. While it is similar to array, it isn't and in VBA for each loop on this collection isn't supported.

If you check IXMLDOMNodeList member, there isn't object list to loop through (only available members are: item, length, nextNode, reset), and only allows access through item() by index.

To my understanding. While VBA tries to loop through for each, there isn't property available and will end up in unspecified error causing Excel to crash.
 
Back
Top