Excerpt from the Dogmatic Constitution n the Church, Lumen Gentium (Pope St. Paul VI, 1964)
In matters of faith and morals, the bishops speak in the name of Christ and the faithful are to accept their teaching and adhere to it with a religious assent. This religious submission of mind and will must be shown in a special way to the authentic magisterium of the Roman Pontiff, even when he is not speaking ex cathedra; that is, it must be shown in such a way that his supreme magisterium is acknowledged with reverence, the judgments made by him are sincerely adhered to, according to his manifest mind and will. His mind and will in the matter may be known either from the character of the documents, from his frequent repetition of the same doctrine, or from his manner of speaking.
Does the Holy Spirit Elect the Pope?
No. The College of Cardinals elects the pope at the conclave which follows the death or resignation of the previous pope. Nonetheless, the cardinals have a grave duty to seek the counsel of the Holy Spirit in making their decision; but they are not enjoined by the Holy Spirit from ignoring His counsel, either. It can also be said, however, that God at least permits each pope who is elected.
How Can the Church Claim the Pope Is Infallible When There's Been So Much Scandal Going Back to the Beginning?
It's important to understand the difference between two important words:
Infallibility -- the belief that the Roman Pontiff cannot err when exercising his teaching authority on behalf of the universal Church, in matters of faith and morals.
Impeccability -- the belief that someone is incapable of committing sin.
The Pope, it cannot be said enough, is human, not divine. No human being has enjoyed an immaculate conception like the Blessed Mother enjoyed. Catholics believe the Holy Spirit teaches through him when he exercises the "office" of pope, but the Holy Spirit does not shield him from making bad personal choices -- sometimes incredibly evil and indefensible choices. The pope needs a savior just like you and me, so while there have been countless saintly popes, the presence of some bad apples along the way does not invalidate the office of the papacy anymore than the presence of Judas invalidated the calling of the Apostles.