汽车之家店铺数据抓取 DotnetSpider实战[一]
优采云 发布时间: 2022-06-09 23:43汽车之家店铺数据抓取 DotnetSpider实战[一]
一、背景
春节也不能闲着,一直想学一下爬虫怎么玩,网上搜了一大堆,大多都是Python的,大家也比较活跃,文章也比较多,找了一圈,发现园子里面有个大神开发了一个DotNetSpider的开源库,很值得庆幸的,该库也支持.Net Core,于是乘着春节的空档研究一下整个开源项目,顺便实战一下。目前互联网汽车行业十分火热,淘车,人人车,易车,汽车之家,所以我选取了汽车之家,芒果汽车这个店铺,对数据进行抓取。
二、开发环境
VS2017+.Net Core2.x+DotNetSpider+Win10
三、开发3.1新建.Net Core项目
新建一个.Net Core 控制台应用
3.2通过Nuget添加DotNetSpider类库
搜索DotnetSpider,添加这两个库就行了
3.3分析需要抓取的网页地址
打开该网页,红框区域就是我们要抓取的信息。
我们通过Chrome的开发工具的Network抓取到这些信息的接口,在里面可以很清楚的知道HTTP请求中所有的数据,包括Header,Post参数等等,其实我们把就是模拟一个HTTP请求,加上对HTML的一个解析就可以将数据解析出来。
参数page就是页码,我们只需要修改page的值就可以获取指定页码的数据了。
返回结果就是列表页的HTML。
3.4创建存储实体类AutoHomeShopListEntity
class AutoHomeShopListEntity : SpiderEntity
{
public string DetailUrl { get; set; }
public string CarImg { get; set; }
public string Price { get; set; }
public string DelPrice { get; set; }
public string Title { get; set; }
public string Tip { get; set; }
public string BuyNum { get; set; }
public override string ToString()
{
return $"{Title}|{Price}|{DelPrice}|{BuyNum}";
}
}
3.5创建AutoHomeProcessor
用于对于获取到的HTML进行解析并且保存
private class AutoHomeProcessor : BasePageProcessor
{
protected override void Handle(Page page)
{
List list = new List();
var modelHtmlList = page.Selectable.XPath(".//div[@class='list']/ul[@class='fn-clear']/li[@class='carbox']").Nodes();
foreach (var modelHtml in modelHtmlList)
{
AutoHomeShopListEntity entity = new AutoHomeShopListEntity();
entity.DetailUrl = modelHtml.XPath(".//a/@href").GetValue();
entity.CarImg = modelHtml.XPath(".//a/div[@class='carbox-carimg']/img/@src").GetValue();
var price = modelHtml.XPath(".//a/div[@class='carbox-info']").GetValue(DotnetSpider.Core.Selector.ValueOption.InnerText).Trim().Replace(" ", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty).TrimStart('¥').Split("¥");
if (price.Length > 1)
{
entity.Price = price[0];
entity.DelPrice = price[1];
}
else
{
entity.Price = price[0];
entity.DelPrice = price[0];
}
entity.Title = modelHtml.XPath(".//a/div[@class='carbox-title']").GetValue();
entity.Tip = modelHtml.XPath(".//a/div[@class='carbox-tip']").GetValue();
entity.BuyNum = modelHtml.XPath(".//a/div[@class='carbox-number']/span").GetValue();
list.Add(entity);
}
page.AddResultItem("CarList", list);
}
}
3.6创建AutoHomePipe
用于输出抓取到的结果。
private class AutoHomePipe : BasePipeline
{
public override void Process(IEnumerable resultItems, ISpider spider)
{
foreach (var resultItem in resultItems)
{
Console.WriteLine((resultItem.Results["CarList"] as List).Count);
foreach (var item in (resultItem.Results["CarList"] as List))
{
Console.WriteLine(item);
}
}
}
}
3.7创建Site