LONDON — Britain’s ruling Conservative Party shed thousands of votes to the insurgent, populist Brexit Party, suffering another crushing election setback early Friday, just hours before Prime Minister Theresa May planned to stand aside as leader.

In a closely watched by-election that was narrowly won by the opposition Labour Party, Mrs. May’s Conservatives were pushed into third place, behind the Brexit Party, led by Nigel Farage.

The result follows the Conservative Party’s disastrous performance in elections for Europe’s parliament last month. Mrs. May’s Tories finished fifth, with just 9 percent of the vote, one the worst performances in their long history.

The defeat in the Peterborough constituency marks another low point for Mrs. May as she ends her leadership of a Conservative Party that has been deeply wounded by her failure to extricate Britain from the European Union, as she had promised to do by the end of March. The election took place on Thursday and the results were declared early Friday.