MADRID — Across much of Europe, Socialist and Social Democratic parties have suffered the fate of many traditional parties. Their once-solid position has been eroded by populist forces and newer parties. The results this week from European Parliament elections mostly confirmed the trend.

But there was one prominent exception: Spain.

Pedro Sánchez, the prime minister, has completed a remarkable comeback by leading his Socialists to victory in national elections on April 28. On Sunday, the Socialists consolidated their gains in Spanish local elections that coincided with those for the European Parliament, finishing first.

The results have now left Mr. Sánchez as the unlikely standard-bearer for a Socialist movement that has crumbled in countries like France, Italy and most recently Germany.

As Mr. Sánchez seeks to form a new Spanish government in coming weeks, his success or failure may become a test of whether Socialism in Europe, outside Scandinavia, has a future after all.