使用C#和HTMLAgility搜索网页

我已经读过HTMLAgility 1.4是一个很好的解压缩网页的解决方案。 作为一名新程序员,我希望我能对这个项目有所了解。 我这样做是作为ac#申请表。 我正在使用的页面非常简单。 我需要的信息只停留在2个标签之间。 我的目标是将Part-Num,Manu-Number,Description,Manu-Country,Last Modified,Last Modified By的数据拉出页面并将数据发送到sql表。 一个转折是还有一个小的png pic,也需要从src =“/ partcode / number中获取。

我没有任何已完成的代码。 我以为这段代码会告诉我我是否朝着正确的方向前进。 即使进入调试我也看不到它做了什么。 有人可能会指出我正确的方向。 越详细越好,因为很明显我需要学习很多东西。 谢谢,我真的很感激。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using HtmlAgilityPack; using System.Xml; namespace Stats { class PartParser { static void Main(string[] args) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml("http://localhost");//my understanding this reads the entire page in? var tables = doc.DocumentNode.SelectNodes("//table");// I assume that this sets up the search for words containing table } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.ReadKey(); } } } } 

网络代码是:

     Part Number Database: Item Record 
Part-Num072140
Manu-Number00721408
DescriptionWidget 3.5
Manu-CountryUnited States
Last Modified26 Jan 2009, 8:08 PM
Last Modified ByManu

查看4GuysFromRolla上的这篇文章

http://www.4guysfromrolla.com/articles/011211-1.aspx

这是我用HTML Agility Pack作为起点的文章,它的效果非常好。 我相信您将从本文中获得所需的所有信息,以执行您尝试完成的任务。

开始部分是关闭的:

 HtmlDocument doc = new HtmlDocument(); doc.LoadHtml("http://localhost"); 

LoadHtml(html)将html字符串加载到文档中,我想你想要这样的东西:

 HtmlWeb htmlWeb = new HtmlWeb(); HtmlDocument doc = htmlWeb.Load("http://stackoverflow.com"); 

根据您提供的HTML源代码,一个工作代码。 它可以是分解的,我不检查值( rowscellscase每个值)。 如果你有127.0.0.1中的页面,那将是有效的。 只需将其粘贴到控制台应用程序Main方法中并尝试理解它。

 HtmlDocument doc = new HtmlWeb().Load("http://127.0.0.1"); var rows = doc.DocumentNode.SelectNodes("//table[@class='data']/tr"); foreach (var row in rows) { var cells = row.SelectNodes("./td"); string title = cells[0].InnerText; var valueRow = cells[2]; switch (title) { case "Part-Num": string partNum = valueRow.SelectSingleNode("./img[@alt]").Attributes["alt"].Value; Console.WriteLine("Part-Num:\t" + partNum); break; case "Manu-Number": string manuNumber = valueRow.SelectSingleNode("./img[@alt]").Attributes["alt"].Value; Console.WriteLine("Manu-Num:\t" + manuNumber); break; case "Description": string description = valueRow.InnerText; Console.WriteLine("Description:\t" + description); break; case "Manu-Country": string manuCountry = valueRow.InnerText; Console.WriteLine("Manu-Country:\t" + manuCountry); break; case "Last Modified": string lastModified = valueRow.InnerText; Console.WriteLine("Last Modified:\t" + lastModified); break; case "Last Modified By": string lastModifiedBy = valueRow.InnerText; Console.WriteLine("Last Modified By:\t" + lastModifiedBy); break; } }