In 1793, Spain went to war against the new French Republic, which had overthrown and executed its Bourbon king, Louis XVI. The war polarised the country in an apparent reaction against the gallicised elites. Defeated in the field, Spain made peace with France in 1795 and effectively became a client state of that country; the following year, it declared war against Britain and Portugal. A disastrous economic situation, along with other factors, led to the abdication of the Spanish king in favour of Napoleon's brother, Joseph Bonaparte.
This new foreign monarch was regarded with scorn. On May 2, 1808, the people of Madrid began a nationalist uprising against the French army, marking the beginning of what is known to the Spanish as the War of Independence, and to the English as the Peninsular War. Napoleon was forced to intervene personally, defeating several badly-coordinated Spanish armies and forcing a British Army to retreat to Corunna. However, further military action by Spanish guerrillas and Wellington's Anglo-Portuguese army, combined with Napoleon's disastrous invasion of Russia, led to the ousting of the French from Spain in 1814, and the return of King Ferdinand VII.
The French invasion proved disastrous for Spain's economy, and left a deeply divided country that was prone to political instability for more than a century. The power struggles of the early 19th century led to the loss of all of Spain's colonies in Latin America, with the exception of Cuba and Puerto Rico.