Example #1
0
        /// <summary>
        /// 오픈api를 접속하여 받아 판매상품수와 샵정보를 리턴한다.
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        public OpenApiDataSetResult OpenApiDataSet(string keyWord)
        {
            int                  total = 0; // 총검색량
            List <string>        titleKeywordListResult = new List <string>();
            OpenApiDataSetResult Result     = new OpenApiDataSetResult();
            List <ShopAPIResult> ShopResult = new List <ShopAPIResult>();

            string  naver = NaverOpenApi(keyWord);
            JObject obj   = JObject.Parse(naver);

            total = Convert.ToInt32(obj["total"]);

            JArray array = JArray.Parse(obj["items"].ToString());

            if (total == 0)              //같은 물품이 없는 경우
            {
                string title       = ""; //검색 결과 문서의 제목을 나타낸다. 제목에서 검색어와 일치하는 부분은 태그로 감싸져 있다.
                string link        = ""; //검색 결과 문서의 하이퍼텍스트 link를 나타낸다.
                string image       = ""; //썸네일 이미지의 URL이다. 이미지가 있는 경우만 나타난다.
                string lprice      = ""; //최저가 정보이다.
                string hprice      = ""; //최고가 정보이다. 최고가 정보가 없거나 가격비교 데이터가 없는 경우 0으로 표시된다.
                string mallName    = ""; //상품을 판매하는 쇼핑몰의 상호이다. 정보가 없을 경우 네이버로 표기된다.
                string productId   = ""; //해당 상품에 대한 ID 이다.
                string productType = ""; //상품군 정보를 일반상품, 중고상품, 단종상품, 판매예정상품으로 구분한다.

                ShopResult.Add(new ShopAPIResult
                {
                    RelKeyword  = keyWord,
                    Title       = title,
                    Image       = image,
                    Lprice      = lprice,
                    Hprice      = hprice,
                    MallName    = mallName,
                    ProductId   = productId,
                    ProductType = productType
                });
            }
            else // 같은 물품이 다수가 있는 경우
            {
                int roop = 0;
                foreach (JObject itemObj in array)
                {
                    if (total == 1)                                             // 검색된 데이터가 한건
                    {
                        string title       = itemObj["title"].ToString();       //검색 결과 문서의 제목을 나타낸다. 제목에서 검색어와 일치하는 부분은 태그로 감싸져 있다.
                        string link        = itemObj["link"].ToString();        //검색 결과 문서의 하이퍼텍스트 link를 나타낸다.
                        string image       = itemObj["image"].ToString();       //썸네일 이미지의 URL이다. 이미지가 있는 경우만 나타난다.
                        string lprice      = itemObj["lprice"].ToString();      //최저가 정보이다.
                        string hprice      = itemObj["hprice"].ToString();      //최고가 정보이다. 최고가 정보가 없거나 가격비교 데이터가 없는 경우 0으로 표시된다.
                        string mallName    = itemObj["mallName"].ToString();    //상품을 판매하는 쇼핑몰의 상호이다. 정보가 없을 경우 네이버로 표기된다.
                        string productId   = itemObj["productId"].ToString();   //해당 상품에 대한 ID 이다.
                        string productType = itemObj["productType"].ToString(); //상품군 정보를 일반상품, 중고상품, 단종상품, 판매예정상품으로 구분한다.

                        if (lprice.Equals(""))
                        {
                            lprice = "0";
                        }

                        if (hprice.Equals(""))
                        {
                            hprice = "0";
                        }


                        title = title.Replace("<b>", "").Replace("</b>", "");
                        List <string> titleKeywordList = title.Split(' ').ToList();
                        titleKeywordListResult.AddRange(titleKeywordList);
                        ShopResult.Add(new ShopAPIResult
                        {
                            RelKeyword       = keyWord,
                            Title            = title,
                            Image            = image,
                            Lprice           = lprice,
                            Hprice           = hprice,
                            MallName         = mallName,
                            ProductId        = productId,
                            ProductType      = productType,
                            TitleKeywordList = titleKeywordList
                        });
                    }
                    else // 검색된 데이터가 다수 인 경우
                    {
                        string title       = itemObj["title"].ToString();//검색 결과 문서의 제목을 나타낸다. 제목에서 검색어와 일치하는 부분은 태그로 감싸져 있다.
                        string link        = itemObj["link"].ToString();        //검색 결과 문서의 하이퍼텍스트 link를 나타낸다.
                        string image       = itemObj["image"].ToString();       //썸네일 이미지의 URL이다. 이미지가 있는 경우만 나타난다.
                        string lprice      = itemObj["lprice"].ToString();      //최저가 정보이다.
                        string hprice      = itemObj["hprice"].ToString();      //최고가 정보이다. 최고가 정보가 없거나 가격비교 데이터가 없는 경우 0으로 표시된다.
                        string mallName    = itemObj["mallName"].ToString();    //상품을 판매하는 쇼핑몰의 상호이다. 정보가 없을 경우 네이버로 표기된다.
                        string productId   = itemObj["productId"].ToString();   //해당 상품에 대한 ID 이다.
                        string productType = itemObj["productType"].ToString(); //상품군 정보를 일반상품, 중고상품, 단종상품, 판매예정상품으로 구분한다.


                        if (lprice.Equals(""))
                        {
                            lprice = "0";
                        }

                        if (hprice.Equals(""))
                        {
                            hprice = "0";
                        }

                        title = title.Replace("<b>", "").Replace("</b>", "");
                        List <string> titleKeywordList = title.Split(' ').ToList();
                        titleKeywordListResult.AddRange(titleKeywordList);
                        ShopResult.Add(new ShopAPIResult
                        {
                            RelKeyword       = keyWord,
                            Title            = title,
                            Image            = image,
                            Lprice           = lprice,
                            Hprice           = hprice,
                            MallName         = mallName,
                            ProductId        = productId,
                            ProductType      = productType,
                            Link             = link,
                            TitleKeywordList = titleKeywordList
                        });
                        roop++;
                    } //검색 데이터 다수 END
                }     // json[items] roop END
            }         // 물품 다수 END

            Result = (new OpenApiDataSetResult {
                TitleKeywordList = titleKeywordListResult, ShopAPIResultList = ShopResult, Total = total
            });
            return(Result);
        }
Example #2
0
        public GridResultData GridDataSet(string KeyWord, int RefMaxCount, SQLiteConnection conn)
        {
            int                       sellPrdCnt       = 0;
            int                       apiUseCount      = 0;
            int                       refAdTotalQcCnt  = 0;
            GridResultData            Result           = new GridResultData();
            List <KeyWordResult>      ADResult         = new List <KeyWordResult>();
            List <KeyWordResult>      RefShopResult    = new List <KeyWordResult>();
            List <KeyWordResult>      SEOResult        = new List <KeyWordResult>();
            List <KeywordList>        RefShopKeyWord   = new List <KeywordList>();
            List <ShopAPIResult>      OpenApiList      = new List <ShopAPIResult>();
            List <String>             TitleKeywordList = new List <string>();
            List <ProductKeyWordList> ProductWordList  = new List <ProductKeyWordList>();


            OpenApiDataSetResult openApiDataSetResult = new OpenApiDataSetResult();
            NaverApi             naverApi             = new NaverApi();
            NaverShoppingCrawler shoppingCrawler      = new NaverShoppingCrawler();

            ReturnToMessage("광고 연관 검색어를 조회합니다..");

            // 네이버 광고 API 실행
            string  naver = naverApi.NaverAdApi(KeyWord.Replace(" ", ""));
            JObject obj   = JObject.Parse(naver);
            JArray  array = null;

            if (obj["keywordList"] != null)
            {
                array = JArray.Parse(obj["keywordList"].ToString());
            }
            else
            {
                ReturnToMessage("-------------------------------------------");
                ReturnToMessage("네이버광고에서 데이터를 불러오지 못했습니다.");
                ReturnToMessage("현재시간과 컴퓨터시간이 오차가 있는지 확인해주세요.");
                ReturnToMessage("오차가 있다면 인터넷 시간서버와 동기화 후 다시 시도해주세요.");
                ReturnToMessage("-------------------------------------------");
                return(Result);
            }

            if (array.Count < 1)
            {
                ReturnToMessage("-------------------------------------------");
                ReturnToMessage("네이버광고에서 데이터를 불러오지 못했습니다.");
                ReturnToMessage("검색된 키워드가 없습니다.");
                ReturnToMessage("-------------------------------------------");
                return(Result);
            }

            // 네이버 키워드 도구 연관 검색어(조회키워드만)
            foreach (JObject itemObj in array)
            {
                string relKeyword             = itemObj["relKeyword"].ToString();             //키워드
                string monthlyPcQcCnt         = itemObj["monthlyPcQcCnt"].ToString();         //월간 pc 검색수
                string monthlyMobileQcCnt     = itemObj["monthlyMobileQcCnt"].ToString();     //월간 모바일 검색수
                string monthlyAvePcClkCnt     = itemObj["monthlyAvePcClkCnt"].ToString();     //월간 PC 클릭수
                string monthlyAveMobileClkCnt = itemObj["monthlyAveMobileClkCnt"].ToString(); //월간 모바일 클릭수
                string monthlyAvePcCtr        = itemObj["monthlyAvePcCtr"].ToString();        //월간 PC 클릭률
                string monthlyAveMobileCtr    = itemObj["monthlyAveMobileCtr"].ToString();    //월간 모바일 클릭률
                string plAvgDepth             = itemObj["plAvgDepth"].ToString();             //경쟁정도
                string compIdx = itemObj["compIdx"].ToString();                               // 월간노출광고수

                monthlyPcQcCnt     = monthlyPcQcCnt.Replace("<", "");
                monthlyMobileQcCnt = monthlyMobileQcCnt.Replace("<", "");



                ReturnToLabel(relKeyword);

                // 네이버 쇼핑 연관 검색어 + 네이버 키워드 도구 연관 검색어
                try
                {
                    openApiDataSetResult = naverApi.OpenApiDataSet(relKeyword); // 오픈API를 상품을 조회한다.
                }
                catch (Exception ex)
                {
                    ReturnToMessage("-------------------------------------------");
                    ReturnToMessage("네이버쇼핑검색과 통신도중 오류가 발생하였습니다.");
                    ReturnToMessage("-------------------------------------------");
                    Console.WriteLine("통신오류: " + ex.ToString());
                }

                sellPrdCnt = openApiDataSetResult.Total; // 키워드의 전체 상품수
                ADResult.Add(new KeyWordResult()
                {
                    RelKeyword = relKeyword, MonthlyPcQcCnt = monthlyPcQcCnt, MonthlyMobileQcCnt = monthlyMobileQcCnt, MonthlyAvePcClkCnt = monthlyAvePcClkCnt, MonthlyAveMobileClkCnt = monthlyAveMobileClkCnt, MonthlyAvePcCtr = monthlyAvePcCtr, MonthlyAveMobileCtr = monthlyAveMobileCtr, PlAvgDepth = plAvgDepth, CompIdx = compIdx, SellPrdQcCnt = sellPrdCnt, ShopResult = openApiDataSetResult.ShopAPIResultList
                });

                apiUseCount++; // 오픈 api 사용량 체크

                // 검색량 조절
                if (RefMaxCount <= apiUseCount)
                {
                    // 조회를 멈춘다.
                    break;
                }
            }

            // api 사용량 DB에 저장
            string           sqlFormattedDate = DateTime.Now.ToString("yyyy-MM-dd");
            string           sql2             = "select* from apicount where apicount.date ='" + sqlFormattedDate + "'";
            SQLiteCommand    cmd = new SQLiteCommand(sql2, conn);
            SQLiteDataReader rdr = cmd.ExecuteReader();

            int    idxRank = 0;
            string count   = string.Empty;

            while (rdr.Read())
            {
                if (idxRank == 0)
                {
                    count = Convert.ToString(rdr["count"]);
                }

                idxRank++;
            }

            Console.WriteLine("데이터베이스 출력 결과: " + count);

            if (string.IsNullOrEmpty(count))
            {
                String        sql     = "insert into apicount (date,count) values('" + sqlFormattedDate + "','" + apiUseCount + "')";
                SQLiteCommand command = new SQLiteCommand(sql, conn);
                int           result  = command.ExecuteNonQuery();
                Console.WriteLine("--------------------------------------");
                Console.WriteLine("데이터베이스 입력결과: " + Convert.ToString(result));
            }
            else
            {
                int           apiTotal = Convert.ToInt32(count) + apiUseCount;
                String        sql      = "update apicount set count='" + apiTotal + "'where date ='" + sqlFormattedDate + "'";
                SQLiteCommand command  = new SQLiteCommand(sql, conn);

                int result = command.ExecuteNonQuery();
                Console.WriteLine("--------------------------------------");
                Console.WriteLine("데이터베이스 입력결과: " + Convert.ToString(result));
            }



            Result = new GridResultData()
            {
                RefAdTotalQcCnt = refAdTotalQcCnt, AdRefGrid = ADResult
            };
            return(Result);
        }