在 C# 中解析 HTML 组合框
我需要解析 html 文件中的选择值。我有这个 html 文件:
<html>
<head></head>
<body>
<select id="region" name="region">
<option value="0" selected>Všetky regiony</option>
<optgroup>Banskobystrický kraj</optgroup>
<option value="k_1">Banskobystrický kraj</option>
<option value="1">Banská Bystrica</option>
<option value="3">Banská Štiavnica</option>
<option value="18">Brezno</option>
<option value="22">Detva</option>
<option value="58">Dudince</option>
</select>
</body>
</html>
我需要获取选择选项值以及字典中的文本值。我在 webBrowser 组件中加载此文件,并尝试通过 ID“region”获取选择标记。
webBrowser1.Url = new Uri("file://\\C:\\1.html");
if (webBrowser1.Document != null)
{
HtmlElement elems = webBrowser1.Document.GetElementById("region");
}
但对象元素为空,我不知道为什么。有预付款吗?
编辑:问题已通过 Html Agillity Pack 解决。谢谢大家。我很愚蠢,我宁愿先听听你对 Html Agillity Pack 的建议。
I need parse a select value in html file. I have this html file:
<html>
<head></head>
<body>
<select id="region" name="region">
<option value="0" selected>Všetky regiony</option>
<optgroup>Banskobystrický kraj</optgroup>
<option value="k_1">Banskobystrický kraj</option>
<option value="1">Banská Bystrica</option>
<option value="3">Banská Štiavnica</option>
<option value="18">Brezno</option>
<option value="22">Detva</option>
<option value="58">Dudince</option>
</select>
</body>
</html>
I need get select option value and also text value in dictionary. I load this file in webBrowser component a try get select tag by ID "region".
webBrowser1.Url = new Uri("file://\\C:\\1.html");
if (webBrowser1.Document != null)
{
HtmlElement elems = webBrowser1.Document.GetElementById("region");
}
But object elems is null, I don’t why. Any advance?
EDIT: Problem was resolved with Html Agillity Pack. Thank for everybody. I was stupid, I had rather listen to your advice with Html Agillity Pack first.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 HtmlAgilityPack 来完成此操作。有很多使用它来解析html的例子。您可以通过谷歌搜索找到。以下是一些:
http://htmlagilitypack.codeplex.com/wikipage?title =Examples&referringTitle=Home
如何使用 HTML Agility pack
更新:
虽然我认为使用该库是更好的选择,但您可以通过以下方式使用网络浏览器控件来完成此操作:
请注意,解析是在 DocumentCompleted 事件处理程序。
You can do it with the HtmlAgilityPack. There are many examples of using it to parsing html. You can find via a google search. Here are a few:
http://htmlagilitypack.codeplex.com/wikipage?title=Examples&referringTitle=Home
How to use HTML Agility pack
UPDATE:
While I think using the library is a better choice, you can do it with the webbrowser control in the following manner:
Notice that the parsing is done in the DocumentCompleted event handler.
Html Agility Pack 是一个出色的 HTML 解析器。
Html Agility Pack is a HTML parser great parser.