As the voting began, two antiwar protestors stood in the gallery and implored lawmakers not to approve more money for the war. “Don’t buy the war! Don’t buy the war!” one woman shouted again and again before being led away by police as the presiding officer of the House banged his gavel to order.

Image From left, Representative Rahm Emanuel, Speaker Nancy Pelosi and Representative John Murtha. Credit... Stephen Crowley/The New York Times

In passing the bill, Ms. Pelosi and other Democratic leaders labored to corral an often-fractious party and presented a near-unified front on the most forceful measure on Iraq that Congress has passed since the Democrats won control of Congress last year. They predicted the outcome would be very close — and it was, with Democrats gaining 218 votes, the bare minimum needed if all 435 members voted. (On Friday, three lawmakers did not vote and one essentially abstained.)

Representative Rahm Emanuel of Illinois, the chairman of the Democratic caucus, noted that each of the freshman Democrats who were elected last year on a wave of discontent supported the legislation. “Everybody came to the conclusion that more of the same — of no change — was not a viable option,” Mr. Emanuel said.

Several of the Democrats who voted against the bill represent conservative Southern districts with large military populations and said they believed the legislation imposed too many conditions on the president. They were joined in their opposition by liberal Democrats who objected to investing more money in a war that has taken the lives of more than 3,200 troops.

Two Republicans voted for the measure: Representative Wayne Gilchrest of Maryland, a former Marine Corps officer who was wounded in Vietnam, and Walter B. Jones of North Carolina, who called for a withdrawal nearly two years ago.

But the rest of the Republican caucus objected to the legislation on substance and principle. Several lawmakers derided the total of nearly $24 billion in domestic spending — benefiting spinach growers and shrimp fishermen and peanut storage, among others — that Democrats put into the bill to make it more palatable to its members.