mlu*_*ker 7 .net c# xml html-parsing
我想解析一个html页面来获取一些数据.首先,我使用SgmlReader将其转换为XML文档.然后,我将结果加载到XMLDocument,然后导航到XPath:
//contains html document
var loadedFile = LoadWebPage();
...
Sgml.SgmlReader sgmlReader = new Sgml.SgmlReader();
sgmlReader.DocType = "HTML";
sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
sgmlReader.InputStream = new StringReader(loadedFile);
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.XmlResolver = null;
doc.Load(sgmlReader);
Run Code Online (Sandbox Code Playgroud)
这个代码适用于大多数情况,除了在这个网站上 - www.arrow.com(尝试搜索像OP295GS这样的东西).我可以使用以下XPath获取包含结果的表:
var node = doc.SelectSingleNode(".//*[@id='results-table']");
Run Code Online (Sandbox Code Playgroud)
这给了我一个带有几个子节点的节点:
[0] {Element, Name="thead"}
[1] {Element, Name="tbody"}
[2] {Element, Name="tbody"}
FirstChild {Element, Name="thead"}
Run Code Online (Sandbox Code Playgroud)
好吧,让我们尝试使用XPath获取一些子节点.但这不起作用:
var childNodes = node.SelectNodes("tbody");
//childnodes.Count = 0
Run Code Online (Sandbox Code Playgroud)
这也是:
var childNode = node.SelectSingleNode("thead");
// childNode = null
Run Code Online (Sandbox Code Playgroud)
甚至这个:
var childNode = doc.SelectSingleNode(".//*[@id='results-table']/thead")
Run Code Online (Sandbox Code Playgroud)
Xpath查询有什么问题?
我刚刚尝试使用Html Agility Pack解析该HTML页面,并且我的XPath查询运行良好.但我的应用程序使用XmlDocument, Html Agility Pack不适合我.
我甚至用Html Agility Pack尝试了以下技巧,但是Xpath查询也不起作用:
//let's parse and convert HTML document using HTML Agility Pack and then load
//the result to XmlDocument
HtmlDocument xmlDocument = new HtmlDocument();
xmlDocument.OptionOutputAsXml = true;
xmlDocument.Load(new StringReader(webPage));
XmlDocument document = new XmlDocument();
document.LoadXml(xmlDocument.DocumentNode.InnerHtml);
Run Code Online (Sandbox Code Playgroud)
也许,网页包含错误(并非所有标签都关闭等等),但尽管如此,我可以看到子节点(通过Visual Studio中的Quick Watch),但无法通过XPath访问它们.
我的XPath查询在Firefox + FirePath + XPather插件中正常工作,但在.net XmlDocument中不起作用:(
老实说,当我尝试从网站获取信息时,我使用正则表达式。Ok Kore Nordmann(在他的 php 博客中)认为,这不好。但有些评论却有不同的说法。
http://kore-nordmann.de/blog/0081_parse_html_extract_data_from_html.html
http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html
但它是用 php 编写的,对此感到抱歉 =) 希望它能有所帮助。
归档时间: |
|
查看次数: |
2106 次 |
最近记录: |