The science that studies the problem you described, is called "spectroscopy". Every element absorbs some of the wavelengths. Same is with molecules. The spectrum is like the footprint of the molecule.
When you observe the light from emitted from some object, you see the continuous spectrum, emited from the light sources (stars, etc.). But it has some black lines present. These are the wavelengths that are absorbed by the molecules and elements. Then you compare it with different spectrums on the Earth (where we can identify the substance) and when you find the same spectrum, you know with a extremely high probability that this is the substance you are searching for.
Example for methanol: Astronomers observed the object with spectroscopy and found the spectrum with some black lines present. They compared it with various other spectra on the Earth and found out, that methanol has same spectral lines. Both measurments can be showed with a graph:
Spectral lines are normally showed with a spectrum (with colors) and some black lines, but this graph shows the dark lines more physically (not all is absorbed) on a graph as deep valleys.
Be aware! There may be redshift present in distant objects. That means, that the lines would shift to the red part of the spectrum. (Similar to Doppler effect.)