[Url= http://www.cnblogs.com/ginohuo/archive/2010/09/28/1837749.html]
偶尔会遇到一些项目需求,从指定网站去挖数据,然后返回执行格式的数据。其实就是一般所说的盗取数据。比如,从以下网页,抓取到一组视频的信息,每条信息包含视频截图,视频名字,Url等等。
[Web]
http://www.tudou.com/albumtop/c30t-1a-1y-1h-1s0p1.html
运行结果
一般而言,首先看看可不可以和对方网站达成合作关系,然后通过一定的Api拿到数据;或许大多数情况都不具备这个条件,然后就是看怎么盗取数据。
一般观察对方是否有一些“隐性”的api(比如给他页面ajax访问的数据api),有的话,悄悄用了。
如果没有,估计就是硬着头皮去分析Html,从中拿到数据了。
使用正则表达式,或者是使用最普通的字符串特征匹配(自己写了if else 逻辑),都能达到结果。
偶尔发现,使用Microsoft.VisualStudio.QualityTools.WebTestFramework.dll中的一些方法,可以帮助分析Html dom. 写了一段代码试了下,留在这里保存下(以防以后需要用的时候,因为某个时候格式化了硬盘,找不到这段代码了)
[Code]
Codeusing System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.WebTesting; using System.IO; using System.Net; namespace HtmlDom2 { class Program { static void Main(string[] args) { Test(); Console.ReadKey(); } private static void Test() { string address = "http://www.tudou.com/albumtop/c30t-1a-1y-1h-1s0p1.html"; WebClient client = new WebClient(); string fileConent = client.DownloadString(address); HtmlTagInnerTextParser parser = new HtmlTagInnerTextParser(fileConent); List<Video> videoList = new List<Video>(); videoList.AddRange(GetVideos(address, parser, "pack pack_album")); videoList.AddRange(GetVideos(address, parser, "pack pack_album hd_video")); Console.WriteLine(videoList.Count); foreach (var item in videoList) { Console.WriteLine(string.Format("{0}:{1}", item.Title, item.ImageUrl)); } } private static List<Video> GetVideos(string address, HtmlTagInnerTextParser parser, string attName) { List<Video> videoList = new List<Video>(); var temp = parser.GetInnerTextForHtmlTags("div", "class", attName, true, false, true); foreach (var item in temp) { HtmlTagInnerTextParser parser2 = new HtmlTagInnerTextParser(item.Value); var temp2 = parser2.GetInnerTextForHtmlTags("div", "class", "pic", true, false, true).ToList(); HtmlDocument doc2 = new HtmlDocument(new Uri(address), temp2[0].Value); string imgeUrl = doc2.HtmlTags.Where(t => t.Name == "img").ToList()[0].GetAttributeValueAsString("src"); var temp3 = parser2.GetInnerTextForHtmlTags("div", "class", "txt", true, false, true).ToList(); HtmlDocument doc3 = new HtmlDocument(new Uri(address), temp3[0].Value); string title = doc3.HtmlTags.Where(t => t.Name == "a" && t.GetAttributeValueAsString("title") != null).ToList()[0].GetAttributeValueAsString("title"); videoList.Add(new Video { ImageUrl = imgeUrl, Title = title }); } return videoList; } } public class Video { public string Title { get; set; } public string ImageUrl { get; set; } } }
注意引用的dll是10.0的就是了