2

I need to scrape some info from web, using vba. This is an extract of my code. It's ok, but the site has 2 classes with the same name. So my code writes only the last value. I want that:

Sheets("01").Range("DW" & number) = source.getAttribute("data-id")

writes only the first value of class "sample" found on site.

How can I do? Thanks

 With http
    .Open "GET", site, False                
    .send
    html.body.innerHTML = .responseText
End With
For Each source In html.getElementsByClassName("sample")

Sheets("01").Range("DW" & number) = source.getAttribute("data-id")  

       
Next source
Next number
1
  • It seems you're not showing all of your (relevant) code. You have a Next number-statement but no matching For or For Each ? Commented Jun 7, 2019 at 14:57

2 Answers 2

2

To refer to the first element of a class collection, you can use the Item property, for which the index is 0-based. So you can replace your For Each/Next with the following line...

Sheets("01").Range("DW" & Number) = html.getElementsByClassName("sample").Item(0).getAttribute("data-id")

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

2

You can be more efficient by using querySelector, which only returns the first match rather than an entire collection (or nodeList)

Sheets("01").Range("DW" & Number) = html.querySelector(".sample").getAttribute("data-id")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.