CANONSBURG, Pa. — The Democrat and Republican in a special House election in the heart of Pennsylvania’s Trump country were divided by a few hundred votes in a race that was too close to call early Wednesday — an ominous sign for Republicans in a district that Donald J. Trump won by nearly 20 percentage points.
With 100 percent of votes counted, Conor Lamb, a Democrat, was clinging to a 641-vote lead over Rick Saccone, a Republican. But one county in the four-county district had not yet counted its absentee ballots, so no winner had been declared as of Wednesday morning. And it was possible that, if Mr. Saccone challenged the results, a legal battle could ensue.
Taking the stage to applause at 12:45 a.m., Mr. Lamb was introduced as “Congressman-elect” and exulted, “It took a little longer than we thought, but we did it!”
House Democrats also did not wait for a final count to claim victory, and House Republicans were already talking about a legal challenge. Under Pennsylvania law, there is no automatic recount in such a race, no matter how close.
But no matter the final outcome, Mr. Lamb’s strong showing demonstrated that the Trump-inspired energy propelling Democrats across the country is not confined to liberal-leaning regions. Republicans were left with the prospect of defending a far broader range of districts this fall than they had hoped.
A first-time candidate and former Marine, Mr. Lamb, 33, forced Republicans to pour over $10 million into a southwestern Pennsylvania district where Democrats did not even field a candidate in the past two congressional elections.
Yet whoever wins here may not hold the seat for very long. The State Supreme Court ruled in January that Pennsylvania’s House map was gerrymandered unlawfully and redrew congressional boundaries that may cause either candidate to run in a new district in November.
Ephemeral as any ultimate victory may be, this contest evolved into a test for both major parties in Trump country. Republicans scrambled to prop up Mr. Saccone, a 60-year-old state representative, mindful that a failure here would send signals well beyond Pittsburgh.
The president appeared twice with Mr. Saccone, most recently at an airport rally on Saturday night in which Mr. Trump mocked Mr. Lamb as “Lamb the sham” and pleaded for voters to support Mr. Saccone. But Mr. Trump also delivered a rambling, 75-minute speech that careened away from the matter at hand.
Republicans concede that they will be unable to keep the 2018 battlefield limited to a few dozen districts, mainly in coastal suburbs where Mr. Trump is intensely unpopular. With a deepening mood of pessimism and fear in Washington, they may be hard-pressed to tackle additional contentious legislation this year.
Even before the returns were counted, Republican officials began criticizing Mr. Saccone’s candidacy in a district where the anti-abortion Republican previously holding the seat, Tim Murphy, was forced to resign after a woman with whom he was having an affair said he pressed her to have an abortion.
But three months after suffering an embarrassing defeat in the special Alabama Senate election, Mr. Trump and his administration once more put their prestige on the line on friendly terrain. By continuing to aggressively compete even as Mr. Lamb was surging, Republicans tested the potency of two of their most fearsome political weapons for the midterm campaigns: their fund-raising advantage and the deep unpopularity of Representative Nancy Pelosi, the House Democratic leader.
Outside organizations sought to derail Mr. Lamb with attacks on his record as a federal prosecutor and claims that he would, as one ad put it, merely be a sheep for Ms. Pelosi.
But the spending did not put the race away, in part because Mr. Lamb pre-emptively inoculated himself against the Pelosi offensive by stating early in the campaign that he would not support her for leader.
Along with his military service and support for gun rights, Mr. Lamb’s opposition to Ms. Pelosi, which he highlighted in a TV ad, helped him win over some of the voters who were raised Democrats but have drifted to the Republican Party in this heavily unionized district.
His approach may signal to other Democrats that they can pursue more moderate swing voters without sacrificing the support of the party’s liberal base, at least in districts that will tolerate deviations from party orthodoxy.
Mr. Lamb confronted a furious attempt by conservatives to retain the seat. In addition to Mr. Trump’s two visits, Vice President Mike Pence appeared with Mr. Saccone, and two of the president’s children did as well, with Donald Trump Jr. here on Monday. Other administration officials also descended on the district, backed up by an advertising offensive by outside Republican groups that began in January.
Few Republicans publicly said Mr. Trump was at fault for the race’s closeness. But their difficulties here, coming mere hours after he abruptly fired Secretary of State Rex W. Tillerson, illustrated how much his chaotic governing style and divisive conduct has unsettled the electorate and presented Democrats the chance to portray themselves as a political safe harbor.
In his remarks early Wednesday morning, Mr. Lamb said, “People are so tired of the shouting on TV and in our politics.”
Mr. Lamb ran a fairly cautious campaign, calling for more cooperation in Washington and largely keeping national Democrats, other than former Vice President Joseph R. Biden Jr., out of the district.
Less than a decade removed from law school, Mr. Lamb, a Marine prosecutor turned assistant United States attorney, said he ran because he wanted to show his party he could compete in working-class white districts and help reconnect Democrats with organized labor.
Mr. Saccone, a mild-mannered Air Force intelligence veteran, aggressively linked himself to Mr. Trump.
“I was Trump before Trump was Trump,” he declared at the outset of the race, and on election eve, he went about proving he could deliver his own set of incendiary remarks.
Standing next to Mr. Trump’s eldest son at a firehouse, Mr. Saccone said Democrats were energized by a hatred for the president, “a hatred for our country” and “a hatred for God.”
Mr. Saccone echoed Mr. Trump’s call for steel tariffs, a popular position in what historically was a steel-and-coal anchored district. But Mr. Lamb also backed the president’s proposed 25 percent tax on imported steel, seeming to blunt an issue that Republicans sought to make central late in the campaign.
Republicans hoped that stamping Mr. Trump’s brand on the race would help mobilize pro-Trump voters who are otherwise mostly tuned out of politics.
But the president’s presence most likely cut both ways, energizing Democrats and disaffected moderates, as well as Mr. Trump’s base. In a rally with Mr. Saccone days before the election, Mr. Trump delivered a heated and unfocused speech, railing about illegal drugs, the Senate confirmation process and news coverage of his administration, and reminiscing about his own victories in 2016. He said relatively little about Mr. Saccone.