The law was approved in Spain's upper house of parliament with 220 votes in favour and 21 against.
It aims to make Spanish law comply with the European Union's General Data Protection Regulation (GDPR) which came into force in May.
Among other things, the GDPR boosts people's right to be forgotten and guarantee free, easy access to personal data.
It also requires businesses to inform people about data breaches that could negatively impact them.
But the Spanish law included an amendment which allows political parties to “use personal data obtained from web pages and other publicly accessible sources to carry out political activities” during election campaign periods.
The law stipulates that people who do not wish to receive targeted adverts from parties should be provided with a “simple and free way to exercise their opposition”.
Under the EU's General Data Protection Regulation, the collection of data regarding people's political opinions could be authorised as long as the appropriate guarantees are given.
The Spanish law was already approved last month by Spain's lower house of parliament and passage in the senate was the final step before it could come into effect.
Spain's Platform for the Defence of Freedom of Information said the law paves the way for parties to create “ideological profiles”.
“It will allow parties to carry out practices like those of Cambridge Analytica”, it said in a statement in a reference to a now defunct British data consultancy which is accused of having harvested the data of millions of Facebook users without their permission.
That data was then allegedly used to direct political advertising at US voters during the 2016 presidential election, as well as to British voters during the referendum that year on Britain's membership in the EU.
Spanish consumer group FACUA and far-left party Unidos Podemos both said in separate statements that they would challenge the law in Spain's Constitutional Court.