Russian Sharapova, the eighth seed, showed all her battling qualities on the clay at the futuristic Magic Box arena to edge world number two Li and set up a semi-final clash with third-seeded Pole Agnieszka Radwanska.
"The match was very close, I think it really could have gone her way today," Sharapova, who saved multiple break points at the end of the second and third sets, told a news conference.
"It was just a matter of a few points in the second set," added the former number one, whose place in the top 10 is under threat after a poor start to the season.
"Although I was up a break throughout the third set, you know, she's not going to let go. I didn't win the match until the last point was played."
Sharapova had beaten Li in four of their last five encounters, including twice on clay, and she said experience had helped her through.
"It's a combination of experience and kind of what you teach yourself and the motivation that you find inside of yourself to not get down when you're feeling things aren't going the exact way that you wanted them to," added the 27-year-old.
"I didn't play a great first set and I found a way to get myself in a position to be in the third.
"Then certainly something changed a little bit and I did something different to get myself going and give myself a bit more energy than I had in the first set."
Sharapova lost to Williams in the 2013 Madrid final and her chances of going one better this year were boosted when the top-ranked American withdrew with a thigh injury before her quarter-final against Czech fifth seed Petra Kvitova.
Williams, winner of the last two editions of the tournament and seeking her 60th career singles title, suffered the injury in her first-round match against Belinda Bencic.
With the French Open just two weeks away she decided to pull out to give herself time to recover.
"It's beyond words. It's so frustrating," Williams said in comments released by the WTA. "This is not the way I wanted this week to end."
The 17-times grand slam singles champion had been on a run of 15 consecutive victories in the Spanish capital and her victory over Carla Suarez Navarro in the last round brought up her 650th win on the women's tour.
Radwanska went through to play Sharapova for a place in Sunday's final after recovering from a second-set dip to see off French qualifier Caroline Garcia 6-4 4-6 6-4.
Fourth seed Simona Halep of Romania cruised past 11th-seeded Serb Ana Ivanovic, another former world number one, 6-2 6-2 and will play Kvitova.
- Sports & Recreation
- Agnieszka Radwanska