Still, Mr. Sánchez has defied the odds before. An economist by training, he was a relative unknown when he was first elected leader of his party, in 2014. His credentials at that point were limited — he had entered Parliament not by winning votes in an election, but as an internal party substitute for a lawmaker who was leaving his seat early.

But the Socialists apparently hoped that a younger, more photogenic leader would allow them to turn the page on the fiasco of 2011, when Mr. Rajoy won a landslide election victory after voters punished the Socialists for Spain’s financial crisis and record unemployment.

By the time Spain held its next election, in 2015, however, Mr. Sánchez was no longer the new kid on the block. Two other parties had emerged — Podemos and Ciudadanos — to break up Spain’s bipartisan politics and take on the established parties with more youthful leaders even than Mr. Sánchez.

Mr. Sánchez led the Socialists to their worst-ever election result, and then lost even worse six months later, when a political deadlock forced Spain to hold another inconclusive vote. After these electoral setbacks, he came under heavy personal criticism, accused of prolonging the deadlock by putting his own ambitions ahead of those of the Socialists and of Spain as a whole.

He behaved like “a fool without scruples,” El País, a Spanish newspaper, wrote in a damning editorial at the time. The campaign to discredit Mr. Sánchez involved heavyweights in the Socialist party, notably Felipe González, a former prime minister.