Thứ Tư, 20 tháng 4, 2011

crawler/grap/spider youtube clip using c# and visual studio 2010

crawler/grap/spider youtube clip using c# and visual studio 2010

download code

Idea:


  1. Using c# and visual studio 2010
  2. Using youtube api to get clip
  3. Robot automatic search by keyword, the process repeats until the end of the clip
Action:


  1. Create console project:
  2. Add class: common:
  3. Add class Proccess to get clip:

  4. In Main method:
  5. Build All project and press F5 to run application

    Enter keyword to search video
  6. Finish
Code in project:

common.cs

public class Common
    {
        public static void AddToDb(Google.YouTube.Video vd)
        {            
            try
            {
                //add video to database
                //...
                
                //alert info video added
                Console.WriteLine((Program.Total++).ToString() + ".added: " + vd.Title);
            }
            catch(Exception ex) {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();                
                Console.ReadKey();
            }
            
        }

        
        public static bool Exits(string title) {
            //check exits video in database
            //...
            return false;
        }
    }

Proccess.cs
class Proccess
    {

        YouTubeRequestSettings settings;
        public Proccess() 
        {
            settings = new YouTubeRequestSettings("trungtv", "AI39si7vt0JJIEr_P-vad29ZDxbG4oKsIwCRwrkiNzcxxwAvRhhFgmufPHiIonVSmNv3iPR9Fy-2BbaHyQ3gqUeC0COFpJL_mw");
        }
        /// <summary>
        /// robot 1
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public Feed<Video> Search(string keyword,bool autoPaging, int numberResult)
        {
            YouTubeRequest request = new YouTubeRequest(settings);

            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);

            //order results by the number of views (most viewed first)
            query.OrderBy = "viewCount";

            // search for puppies and include restricted content in the search results
            // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
            query.Query = keyword;
            //query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
            query.NumberToRetrieve = numberResult;

            //query.StartIndex = 1;

            Feed<Video> videoFeed = request.Get<Video>(query);

            videoFeed.AutoPaging = autoPaging;

            return videoFeed;
        }
        /// <summary>
        /// robot 2
        /// </summary>
        /// <param name="playlistID"></param>
        /// <returns></returns>
        public Feed<Video> GetByPlaylistID(string PlaylistID)
        {
            YouTubeRequest request = new YouTubeRequest(settings);
            YouTubeQuery query = new YouTubeQuery("http://gdata.youtube.com/feeds/api/playlists/" + PlaylistID);

            //order results by the number of views (most viewed first)
            query.OrderBy = "viewCount";            

            Feed<Video> videoFeed = request.Get<Video>(query);

            videoFeed.AutoPaging = true;

            return videoFeed;

        }
        /// <summary>
        /// robot 3
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public Feed<Video> GetByUsers(string userid)
        {
            YouTubeRequest request = new YouTubeRequest(settings);
            var feed = request.GetVideoFeed(userid);
            feed.AutoPaging = true;
            return feed;
        }
        /// <summary>
        /// robot 4
        /// </summary>
        /// <param name="ListVideoID">Ex:PO7WwmRQ7HA,PO7WwmRQ7HA,PO7WwmRQ7HA</param>
        /// <returns></returns>
        public List<Video> GetList(string ListVideoID)
        {
            YouTubeRequest request = new YouTubeRequest(settings);

            List<Video> lst = new List<Video>();

            var arr = ListVideoID.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string vid in arr)
            {
                Video video = request.Retrieve<Video>(new Uri("http://gdata.youtube.com/feeds/api/videos/" + vid));
                lst.Add(video);
            }
            return lst;
        }
        /// <summary>
        /// robot 5
        /// </summary>
        /// <param name="vd"></param>
        public void GetVideo(Video vd, int level)
        {
            try
            {
                //check
                if (Common.Exits(vd.Title))
                    return;

                //check category
                bool enable = false;
                foreach (var item in vd.Categories) {
                    if (item.Label!=null && System.Configuration.ConfigurationManager.AppSettings.Get("category_fun").Contains(item.Label))
                    { enable = true; break; }
                }
                if (!enable)
                    return;

                //add to db
                Common.AddToDb(vd);

                //check level
                if (level >= Program.Level_Max)
                    return;
                
                //get video relate
                var lstRelate = new List<Video>();
                foreach (Video item in GetByRelate(vd).Entries)
                {
                    if (!Common.Exits(item.Title))
                        lstRelate.Add(item);
                }
                var crawl_relate = new Crawl(lstRelate, level + 1);
                new System.Threading.Thread(new System.Threading.ThreadStart(crawl_relate.Start)).Start();
                
                //get by users
                var lstUser = new List<Video>();
                foreach (Video item in GetByUsers(vd.Author).Entries)
                {
                    if (!Common.Exits(item.Title))
                        lstUser.Add(item);        
                }
                var crawl_users = new Crawl(lstUser, level + 1);
                new System.Threading.Thread(new System.Threading.ThreadStart(crawl_users.Start)).Start();

            }
            catch { 
                //log
            }
        }
        public PlaylistFeed GetPlayList(string PlaylistID) 
        {
            YouTubeRequest request = new YouTubeRequest(settings);
            YouTubeQuery query = new YouTubeQuery("http://gdata.youtube.com/feeds/api/playlists/" + PlaylistID);
            var pl = request.Service.GetPlaylist(query);
            return pl;
        }
        public Playlist GetPlaylist(PlaylistFeed pl) 
        {
            YouTubeRequest request = new YouTubeRequest(settings);
            var playlist = request.GetPlaylistsFeed(pl.Authors.FirstOrDefault().Name).Entries.Single(c => c.Title == pl.Title.Text);
            return playlist;       
        }
        public Feed<Video> GetByRelate(Video vd)
        {
            YouTubeRequest request = new YouTubeRequest(settings);
            var feed = request.GetRelatedVideos(vd);
            feed.AutoPaging = true;
            return feed;
        }
    }

    class Crawl 
    {
        Video vd;
        List<Video> lst_vd;
        int level;

        public Crawl(Video _vd,int _level) {
            vd = _vd;
            level = _level;
        }
        public Crawl(List<Video> _lstvd, int _level)
        {
            lst_vd = _lstvd;
            level = _level;
        }

        public void Start() {
            foreach (var item in lst_vd)
                new Proccess().GetVideo(item, level);

        }
    }
Program.cs
class Program
    {
        public static int Level = 0;
        public static int Level_Max = 2;
        public static int Total = 1;

        static void Main(string[] args)
        {

            Console.Write("Keyword to crawl: ");

            string key = Console.ReadLine();

            var feed = new Proccess().Search(key, false, 10);

            foreach(Google.YouTube.Video item in feed.Entries)
            {
                new Proccess().GetVideo(item, 0);
            }
            
            Console.ReadKey();
        }

    }
Wish you success! 

Không có nhận xét nào:

Đăng nhận xét