How does the media know how people voted? Watch
On the days of actual elections there are exit polls, too.
They don't know. They extrapolate from surveys. polls etc. As they later dig down into the figures, they may find that the first impressions are wrong. The latest idea is that Labour did very well with Remain voters in Leave seats.
Of course the modelling is likely a lot more sophisticated these days, social media playing a significant part and different companies using diverging methodologies, which may be why polls these days seem to contradict one another so much.
We should never just ignore statistical analysis but we should be very cautious accepting without question the conclusions drawn from the data, flaws do get missed. (see recent Naomi Woolf controversy re data possibly/likely being misunderstood as an example)