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

标签 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>

如果我需要名为'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>

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

this is a <b>left</b> side:<div style='color:red'> 1 </div>

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

 main side

我该怎么办?

最佳答案

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

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

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

关于c# - 如何在C#中使用正则表达式通过id获取html div元素的innertext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1431391/

相关文章:

Ruby - 提取正则表达式捕获组的最佳方式?

c# - 如何在 Fluent-NHibernate 中级联插入父级、子级和组合列表

c# - 将绘图从类发送到 C# 中的窗体

c# - 从 Universal 8.1 App 的 App.xaml 中的共享项目访问 Windows Phone 项目中的 ResourceDictionary

c# - Moonsharp pairs(...) 接下来引发异常 "bad argument #1 to ''(预期表,得到字符串)”

regex - 在 Perl 正则表达式中使用量词而不是仅仅重复字符是否有令人信服的理由?

regex - 在以 "/"分隔的字符串中查找重复的单词

java - Java中使用正则表达式屏蔽最后4位数字

java - 通过定义正则表达式过滤日志文件

c# - 在类下的 CSS 中显示背景图像