LONDON — In a surprise upset, a candidate of the centrist and pro-European Liberal Democrats defeated a prominent supporter of British withdrawal from the European Union in a parliamentary by-election on Thursday.

The victory, by Sarah Olney, delivered a badly needed lift to the Liberal Democrats, who were in danger of becoming extinct after disastrous losses in last year’s national elections, and it highlighted some of the deep divisions in Britain over its looming departure from the European Union, commonly referred to as Brexit.

In the election in the Richmond Park and North Kingston constituency in southwest London, Ms. Olney had 20,510 votes, to 18,638 for Zac Goldsmith, according to results announced early Friday.

Mr. Goldsmith won the same seat for the governing Conservative Party only last year, and by more than 23,000 votes. He resigned from Parliament in protest over government plans to expand Heathrow Airport — a project that is unpopular locally.