2、获取具体商品信息
(1)首先根据商品分类加载分类信息,获取到当前分类每个页面的链接
下载HTML之后,选择节点,可以将HTML格式化之后查看每个页面的url地址和拼接规则,然后借助HtmlAgilityPack
来筛选需要的节点,将每个页面的url分离出来
try
{
string html = HttpHelper.DownloadUrl(@"https://www.easck.com/list.html?cat=1620,11158,11964");
HtmlDocument productDoc = new HtmlDocument();
productDoc.LoadHtml(html);
HtmlNode pageNode = productDoc.DocumentNode.SelectSingleNode(@"//*[@id='J_topPage']/span/i");
if (pageNode != null)
{
int pageNum = Convert.ToInt32(pageNode.InnerText);
for (int i = 1; i < pageNum + 1; i++)
{
string pageUrl = string.Format("{0}&page={1}", category.Url, i).Replace("&page=1&", string.Format("&page={0}&", i));
try
{
List<ProductInfo> proDuctInfo = GetPageProduct(pageUrl);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
(2)根据每个页面的链接,获取当前页面的商品信息
下载每个页面的所有商品信息,需要获取的商品信息在页面中都能找到
首先我们获取到每个商品的节点集合,获取到一个商品的节点信息之后,分析html数据,
找到我们需要的商品的信息所在的位置,然后将需要的信息分离出来。
下面的代码中我获取到的商品的id和title还有价格。
List<ProductInfo> productInfoList = new List<ProductInfo>();
try
{
string html = HttpHelper.DownloadUrl(url);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection productNodeList = doc.DocumentNode.SelectNodes("//*[@id='plist']/ul/li");
if (productNodeList == null || productNodeList.Count == 0)
{
return productInfoList;
}
foreach (var node in productNodeList)
{
HtmlDocument docChild = new HtmlDocument();
docChild.LoadHtml(node.OuterHtml);
ProductInfo productInfo = new ProductInfo()
{
CategoryId = category.Id
};
HtmlNode urlNode = docChild.DocumentNode.SelectSingleNode("//*[@class='p-name']/a");
if (urlNode == null)
{
continue;
}
string newUrl= urlNode.Attributes["href"].Value;
newUrl = !newUrl.StartsWith("http:")?"http:" + newUrl: newUrl;
string sId = Path.GetFileName(newUrl).Replace(".html", "");
productInfo.ProductId = long.Parse(sId);
HtmlNode titleNode = docChild.DocumentNode.SelectSingleNode("//*[@class='p-name']/a/em");
if (titleNode == null)
{
continue;
}
productInfo.Title = titleNode.InnerText;
HtmlNode priceNode = docChild.DocumentNode.SelectSingleNode("//*[@class='p-price']/strong/i");
if (priceNode == null)
{
continue;
}
else
{
}
productInfoList.Add(productInfo);
}
//批量获取价格
GetGoodsPrice(productInfoList);
}
catch (Exception ex)
{
}
return productInfoList;










