The dwarves were captured by the wood-elves in Mirkwood shortly after Bilbo had rescued them from the spiders. Bilbo was not captured at the time because he was wearing the magic ring he won from Gollum. The ring made the wearer invisible. Here is what happened:
Bilbo attacked the spiders that were tying the dwarves up in their webs. By shouting at them and throwing a couple of stones, Bilbo led the spiders away from the dwarves, still wearing his ring. Then he craftily returned back to the dwarves to release them from their bonds. Shortly thereafter the Mirkwood elves surrounded and took all the dwarves prisoner, excluding Bilbo, of course, because he still wore the magic ring. Fortunately for the dwarves, Bilbo remains unseen, because eventually he will help them escape the Elven King's dungeons.
Bilbo and most of the dwarves are captured by giant spiders. Bilbo defeats the spider nearest him using his small sword, which he then names Sting. He then cuts himself free with Sting. He sneaks around by wearing his magic ring, which makes him invisible. After finding the dwarves hanging from spider webs, he lures the spiders away and frees them from their bonds.
The party then realizes that Thorin is missing. This is because the elves have already captured him. When the elves arrive and capture the other dwarves, Bilbo evades escape because the ring makes him invisible. This allows him to remain free and help his friends yet again.
The ring gets Bilbo out of a lot of troubling situations like this one. In subsequent books, we learn more about the dark side of this item, but for now Bilbo just thinks of it as a useful way to become invisible.