First they have to be marked. Marking the atoms means their ionisation, i.e. removing one (or more) electrons. It is a delicate process – a rude ionisation leads not only to “defoliation” from electrons, but to a defragmentation of the whole molecule, in a way making it difficult to recognize from fragments how it looked like before.
Many ways exist for “weighting”: charged atom or molecule (usually positively charged, but sometimes negatively) is subjected to electric fields and/or to magnetic fields. First mass spectrometer was built by Aston in 1919 and it was magnetostatic one. With this spectrometer he discovered that, chemically the same atoms (like neon) can have different masses; in this way “hunting” for neutrons started. Constant electric field is used in time-of-flight spectrometer and alternate field is used in quadrupole spectrometer.
Accuracy of the nowadays spectrometers is so big, that they allows not to only intentify components but chemical energy of the bonds (via Einstein’s mass defect).
Ionisation can be performed in new ways: with quick lasers, electron beam, positrons and lately by association of the proton (originating from ionized water H3O+). Especially the lattest method allows to identify chemical substances with incredible sensitivity, avoiding their fragnentation.
The flavour of strawberries? – we know just in this way.