Williams was due to face Petra Kvitova in the quarter-finals but pulled out due to a thigh injury she had been carrying since sweeping aside Swiss teenager Belinda Bencic in the first round on Sunday.
"I have a left thigh injury and, unfortunately, have to withdraw from this year's Madrid Open," said Williams.
"It happened during my first round match. It started to get better, but most importantly right now, I just need some time to rest and recover.
However, the American insisted that she will try to defend her title at the Internazionale BNL D'Italia in Rome next week.
More From This Section
"I am planning to play in Rome. Fortunately, I have a bye next week so will have an extra day of rest.
"For now, I will take it one day at a time and take advantage of some extra rest."
Sharapova has been beaten by Williams in Madrid in the last two years, including in the 2013 final, and the Russian is now the favourite to clinch her first title in the Spanish capital as she edged a thrilling match against second seed Li 2-6, 7-6 (7/5), 6-3.
However, Sharapova broke back immediately and, despite needing four set points, finally forced the match into a deciding set when Li netted at 5-6 down in the tie-break.
There were three breaks of serve to open the third set, but Sharapova took control when she finally consolidated the break at 3-1 and was gifted the final game when Li double faulted on match point.
The four-time Grand Slam champion will face third seed Agnieszka Radwanska or French qualifier Caroline Garcia in the semi-finals tomorrow.