....from Jimmy Akin:
God Guides the Church
We can be confident of the general principle that God guides his Church. This is something we have biblical assurance of.
But his guidance does not prevent human free will from operating, and that means there is the potential for humans to abuse their free will. That applies to the college of cardinals, too, even when they are electing a pope. They do not lose their free will.
Human Failure in History
We have been very fortunate in recent times to have a series of very holy, wise popes, but this has not always been the case.
If you look at history, certain popes have been real scoundrels, like Pope Benedict IX (first elected in 1032).
He was elected pope when still a boy. His reign was scandalous. He insisted upon monetary compensation in order to get him to resign. And then he didn't stay resigned. He was the only man to ever hold the papacy more than once. (In fact, he may have held it as many as three times.)
Without going into all the scandals attributed to him, the Catholic Encyclopedia states: "He was a disgrace to the Chair of Peter."