如何在C#中使用正则表达式通过id获取html div元素innertext

eba*_*lga 3 c# regex

我正在使用 WebClient 获取完整的 html 代码。但我需要使用正则表达式从完整的 html 中获取指定的 div。

例如:

<body>
<div id="main">
     <div id="left" style="float:left">this is a <b>left</b> side:<div style='color:red'> 1 </div>
     </div>
     <div id="right" style="float:left"> main side</div>
<div>
</body>
Run Code Online (Sandbox Code Playgroud)

如果我需要名为“main”的 div,函数返回

<div id="left" style="float:left">this is a <b>left</b> side:<div style='color:red'> 1 </div>
     </div>
     <div id="right" style="float:left"> main side</div>
Run Code Online (Sandbox Code Playgroud)

如果我需要名为“left”的 div,函数返回

this is a <b>left</b> side:<div style='color:red'> 1 </div>
Run Code Online (Sandbox Code Playgroud)

如果我需要名为“right”的 div,函数返回

 main side
Run Code Online (Sandbox Code Playgroud)

我能怎么做?

Mar*_*ell 5

为什么人们坚持尝试使用正则表达式来解析 html?如果排除大量边缘情况,您可能可以做到这一点...但只需使用HTML Agility Pack即可完成:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(...); // or Load
string main = doc.DocumentNode.SelectSingleNode("//div[@id='main']").InnerHtml;
Run Code Online (Sandbox Code Playgroud)

(注意我假设它不是 xhtml;如果它是 xhtml,请使用XmlDocumentXDocument,以及与上面非常相似的代码)