Prestige, and also to ensure the legitimacy of the children. In Germany in the period, you began to see Morgantic marriages, such as with the Landgrave of Hesse and his bigamous marriage. By marrying into other sovereign houses it ensured it was an equal match. France didn't have morgantic marriages, but there were secret marriages, such as Louis XIV with Madame de Maintagnon. Marriage of Princes became in France required the King's consent. Gaston d'Orléans married a daughter of the Duke of Lorraine and the marriage was considered void because the King's consent was not granted for instance, although theoretically it was an equal marriage.
It's not a huge problem that they married cousins or such close relatives, it's the fact that it continued over such a long period. If one of the Spanish Kings had gotten a bit luckier and had a surviving son with his French wife, it would've given their tree a little bit of breathing room. Charles II's family tree is messed up precisely because it is four generations of nieces giving birth to their uncles children. His own birth was bad luck, considering Philip IV and Marianna had a perfectly healthy daughter.