我正在学习如何使用HTML Agility Pack来抓取页面,但不知道该怎么做。
例如,这里有一个页面:http://gtin13.com/query.jsp?query=Hunts
我希望将以下内容添加到数据库中:
Field1:Hunts Sp Pdg Chc Fdg
Field2:14 Oz
Field3:Size 12 ct
Field4:0027000411766
Field5:00-27000-41176-6
Field6:027000411766
Field7:02700041176
每页有几个这样的页面。
下面是HTML的一部分:
<div class="PostContent">
<b><a href="/product/hunts+sp+pdg+chc+fdg+14+00+oz/">Hunts Sp Pdg Chc Fdg 14.00 Oz</a></b><br />
Size: 12 ct<br />
GTIN/EAN-13: 0027000411766 / 00-27000-41176-6<br />
UPC-A: 027000411766 / 02700041176<br />
Tags:
<a href="/tag/hunts/">Hunts</a>,
..<br />
<br >
<b><a href="/product/m-hunts+snk+pk+chc+var/">M-Hunts Snk Pk Chc Var</a></b><br />
Size: 14 oz<br />
GTIN/EAN-13: 0027000410868 / 00-27000-41086-8<br />
UPC-A: 027000410868 / 02700041086<br />
<br >
<b><a href="/product/hunts+snk+pk+mud+pie+4pk/">Hunts Snk Pk Mud Pie 4pk</a></b><br />
Size: 14 oz<br />
GTIN/EAN-13: 0027000412817 / 00-27000-41281-7<br />
UPC-A: 027000412817 / 02700041281<br />
<br >
</div>我该怎么做呢?
发布于 2011-10-16 14:26:57
这是可能的,但并不容易。不幸的是,内容的布局很笨拙。你只需要一点点的努力就行了。看一下上面列出的一些东西,我看不到任何有意义的方法来确定您的Field2部件应该是什么。
给定一个类来保存您的数据:
public class Data
{
public string Name { get; set; }
public string Size { get; set; }
public string Gtin { get; set; }
public string Ean13 { get; set; }
public string Upc { get; set; }
public string UpcA { get; set; }
}获取数据的步骤:
var web = new HtmlWeb();
var doc = web.Load("http://gtin13.com/query.jsp?query=Hunts");
var sections = doc.DocumentNode.SelectNodes("//div[@class='PostContent']/b");
var result = new List<Data>();
foreach (var header in sections)
{
var data = new Data();
data.Name = header.InnerText.Trim();
var currentField = header.NextSibling.NextSibling;
var sizeMatch = Regex.Match(currentField.InnerText.Trim(), @"Size: (.+)");
if (sizeMatch.Success)
{
data.Size = sizeMatch.Groups[1].Value;
currentField = currentField.NextSibling.NextSibling;
}
var gtinMatch = Regex.Match(currentField.InnerText.Trim(), @"GTIN/EAN-13: (\S+) / (\S+)");
if (gtinMatch.Success)
{
data.Gtin = gtinMatch.Groups[1].Value;
data.Ean13 = gtinMatch.Groups[2].Value;
currentField = currentField.NextSibling.NextSibling;
}
var upcMatch = Regex.Match(currentField.InnerText.Trim(), @"UPC-A: (\S+) / (\S+)");
if (upcMatch.Success)
{
data.Upc = upcMatch.Groups[1].Value;
data.UpcA = upcMatch.Groups[2].Value;
}
result.Add(data);
}https://stackoverflow.com/questions/5490733
复制相似问题