汽车之家店铺数据抓取 DotnetSpider实战
一、背景
春節(jié)也不能閑著,一直想學(xué)一下爬蟲怎么玩,網(wǎng)上搜了一大堆,大多都是Python的,大家也比較活躍,文章也比較多,找了一圈,發(fā)現(xiàn)園子里面有個(gè)大神開發(fā)了一個(gè)DotNetSpider的開源庫(kù),很值得慶幸的,該庫(kù)也支持.Net Core,于是乘著春節(jié)的空檔研究一下整個(gè)開源項(xiàng)目,順便實(shí)戰(zhàn)一下。目前互聯(lián)網(wǎng)汽車行業(yè)十分火熱,淘車,人人車,易車,汽車之家,所以我選取了汽車之家,芒果汽車這個(gè)店鋪,對(duì)數(shù)據(jù)進(jìn)行抓取。
二、開發(fā)環(huán)境
VS2017+.Net Core2.x+DotNetSpider+Win10
三、開發(fā)
3.1新建.Net Core項(xiàng)目
新建一個(gè).Net Core 控制臺(tái)應(yīng)用
3.2通過(guò)Nuget添加DotNetSpider類庫(kù)
搜索DotnetSpider,添加這兩個(gè)庫(kù)就行了
?3.3分析需要抓取的網(wǎng)頁(yè)地址
打開該網(wǎng)頁(yè)https://store.mall.autohome.com.cn/83106681.html,紅框區(qū)域就是我們要抓取的信息。
我們通過(guò)Chrome的開發(fā)工具的Network抓取到這些信息的接口,在里面可以很清楚的知道HTTP請(qǐng)求中所有的數(shù)據(jù),包括Header,Post參數(shù)等等,其實(shí)我們把就是模擬一個(gè)HTTP請(qǐng)求,加上對(duì)HTML的一個(gè)解析就可以將數(shù)據(jù)解析出來(lái)。
參數(shù)page就是頁(yè)碼,我們只需要修改page的值就可以獲取指定頁(yè)碼的數(shù)據(jù)了。
返回結(jié)果就是列表頁(yè)的HTML。
?3.4創(chuàng)建存儲(chǔ)實(shí)體類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創(chuàng)建AutoHomeProcessor
用于對(duì)于獲取到的HTML進(jìn)行解析并且保存
private class AutoHomeProcessor : BasePageProcessor
? ? ? ? {
? ? ? ? ? ? protected override void Handle(Page page)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? List<AutoHomeShopListEntity> list = new List<AutoHomeShopListEntity>();
? ? ? ? ? ? ? ? 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創(chuàng)建AutoHomePipe
用于輸出抓取到的結(jié)果。
private class AutoHomePipe : BasePipeline
? ? ? ? {
? ? ? ? ? ? public override void Process(IEnumerable<ResultItems> resultItems, ISpider spider)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? foreach (var resultItem in resultItems)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? Console.WriteLine((resultItem.Results["CarList"] as List<AutoHomeShopListEntity>).Count);
? ? ? ? ? ? ? ? ? ? foreach (var item in (resultItem.Results["CarList"] as List<AutoHomeShopListEntity>))
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(item);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
3.7創(chuàng)建Site
主要就是將HTTP的Header部信息放進(jìn)去
var site = new Site
? ? ? ? ? ? {
? ? ? ? ? ? ? ? CycleRetryTimes = 1,
? ? ? ? ? ? ? ? SleepTime = 200,
? ? ? ? ? ? ? ? Headers = new Dictionary<string, string>()
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? { "Accept","text/html, */*; q=0.01" },
? ? ? ? ? ? ? ? ? ? { "Referer", "https://store.mall.autohome.com.cn/83106681.html"},
? ? ? ? ? ? ? ? ? ? { "Cache-Control","no-cache" },
? ? ? ? ? ? ? ? ? ? { "Connection","keep-alive" },
? ? ? ? ? ? ? ? ? ? { "Content-Type","application/x-www-form-urlencoded; charset=UTF-8" },
? ? ? ? ? ? ? ? ? ? { "User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36"}
? ? ? ? ? ? ? ? }
? ? ? ? ? ? };
3.8構(gòu)造Request
因?yàn)槲覀兯ト〉降慕涌诒仨氂肞OST,如果是GET請(qǐng)求則這一部可以省略,參數(shù)就放在PostBody就行。
List<Request> resList = new List<Request>();
? ? ? ? ? ? for (int i = 1; i <= 33; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Request res = new Request();
? ? ? ? ? ? ? ? res.PostBody = $"id=7&j=%7B%22createMan%22%3A%2218273159100%22%2C%22createTime%22%3A1518433690000%2C%22row%22%3A5%2C%22siteUserActivityListId%22%3A8553%2C%22siteUserPageRowModuleId%22%3A84959%2C%22topids%22%3A%22%22%2C%22wherePhase%22%3A%221%22%2C%22wherePreferential%22%3A%220%22%2C%22whereUsertype%22%3A%220%22%7D&page={i}&shopid=83106681";
? ? ? ? ? ? ? ? res.Url = "https://store.mall.autohome.com.cn/shop/ajaxsitemodlecontext.jtml";
? ? ? ? ? ? ? ? res.Method = System.Net.Http.HttpMethod.Post;
? ? ? ? ? ? ? ? resList.Add(res);
? ? ? ? ? ? }
3.9構(gòu)造爬蟲并且執(zhí)行
var spider = Spider.Create(site, new QueueDuplicateRemovedScheduler(), new AutoHomeProcessor()).AddStartRequests(resList.ToArray()).AddPipeline(new AutoHomePipe());spider.ThreadNum = 1;spider.Run();3.10執(zhí)行結(jié)果
四、下次預(yù)告
接下來(lái)我會(huì)將對(duì)商品的詳情頁(yè)數(shù)據(jù)(包括車型參數(shù)配置之類的)進(jìn)行抓取,接口已經(jīng)抓取到了,還在思考如果更加便捷獲取到商品id,因?yàn)槟壳皝?lái)看商品id是存儲(chǔ)在頁(yè)面的js全局變量中,抓取起來(lái)比較費(fèi)勁。
五、總結(jié)
.Net 相對(duì)于別的語(yǔ)言感覺并不是那么活躍,DotnetSpider雖然時(shí)間不長(zhǎng),但是希望園子里面大伙都用起來(lái),讓他不斷的發(fā)展,讓我們的.Net能夠更好的發(fā)展。
原文地址:?https://www.cnblogs.com/FunnyBoy/p/8453338.html
總結(jié)
以上是生活随笔為你收集整理的汽车之家店铺数据抓取 DotnetSpider实战的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。