Example #1
0
        public List <level1link> Query(searchkeyword tsk, keyword businessKeyword, List <keyword> businessKeywords, List <keyword> excludedKeywords)
        {
            List <level1link> result = new List <level1link>();

            var links = get_urls(tsk, businessKeyword);

            if (links == null || links.Count == 0)
            {
                return(null);
            }


            foreach (var link in links)
            {
                try
                {
                    GetLinks(link, tsk, businessKeyword, businessKeywords, excludedKeywords);
                    //if (list != null && list.Count > 0)
                    //    result.AddRange(list);
                }
                catch (Exception ex)
                {
                    log(ex.Message + ex.StackTrace);
                }
            }


            return(result);
        }
        public void save_level1_links(List <level1link> links,
                                      searchkeyword tsk, List <keyword> excludedKeywords)
        {
            links = prehandle_data(links, tsk, excludedKeywords);

            if (links == null || links.Count == 0)
            {
                log("SUCCESS saving 0 Level 1 Links for " + tsk.Keyword);
                return;
            }

            int pagesize = 100;
            int count    = 0;
            var col      = MongoDBHelper.Instance.Getlevel1links();
            var builder  = Builders <level1link> .Filter;

            for (int page = 0; page *pagesize < links.Count; page++)
            {
                var list = links.Skip(page * pagesize).Take(pagesize).ToList();
                //list.ForEach(x => x._id = new MongoDB.Bson.ObjectId(IDHelper.GetGuid("{0}/&itemid={1}".FormatStr(x.Domain, x.LinkUrl)).ToString()));
                list = ListDistinctBy(list, x => x.BizId);

                FieldsDocument fd = new FieldsDocument();
                fd.Add("BizId", 1);

                List <Guid> bizIds      = list.Select(x => x.BizId).ToList();
                var         exists_objs = col.Find(builder.In(x => x.BizId, bizIds)).Project(x => x.BizId).ToList();
                List <Guid> exists_ids  = new List <Guid>();
                foreach (var result in exists_objs)
                {
                    exists_ids.Add(result);
                }
                if (exists_ids != null && exists_ids.Count > 0)
                {
                    list = list.Where(x => !exists_ids.Contains(x.BizId)).ToList();
                }
                if (list == null || list.Count == 0)
                {
                    continue;
                }
                count += pagesize;

                col.InsertMany(links);
                log("SUCCESS saving " + links.Count + " Level 1 Links for " + tsk.Keyword);
            }
        }
        private void query(searchkeyword p)
        {
            try
            {
                var builder = Builders <keyword> .Filter;
                var filter  = builder.Eq(x => x.UsrId, p.UsrId);

                var excludedKeywords = MongoDBHelper.Instance.Getiws_excludekeywords().Find(filter).ToList();
                var businessKeywords = MongoDBHelper.Instance.Getiws_businesskeywords().Find(filter).ToList();

                log("loaded {0} excluding keywords ".FormatStr(excludedKeywords == null ? 0 : excludedKeywords.Count));
                if (excludedKeywords.GetCount() > 0)
                {
                    excludedKeywords.ForEach(x => x.Txt = x.Txt.ToLower());
                }

                try
                {
                    foreach (var busKey in businessKeywords)
                    {
                        Queries.BaiduQuery baidu = new Queries.BaiduQuery(p.Keyword + busKey.Txt);

                        var links = baidu.Query(p, busKey, businessKeywords, excludedKeywords);
                        //save_level1_links(links, p, excludedKeywords);

                        //SogouWeixin sogou = new SogouWeixin(tsk.Keyword);
                        //links = sogou.Query(tsk);
                        //save_level1_links(links, tsk, excludedKeywords);
                    }
                }
                catch (Exception ex)
                {
                    log(ex.Message);
                }
            }
            catch (Exception ex)
            {
                log(ex.Message);
            }
        }
Example #4
0
        List <string> get_urls(searchkeyword tsk, keyword businessKeywords)
        {
            var           searchKeywords = tsk.Keyword.RemoveSpace().GetLower().Split(';');
            List <string> kws            = new List <string>();

            foreach (var t in searchKeywords)
            {
                if (string.IsNullOrEmpty(t))
                {
                    continue;
                }


                kws.Add("{0}{1}".FormatStr(t, businessKeywords.Txt));
            }

            string baiduUrlFormat = "http://www.baidu.com/s?ie=utf-8&wd={0}";

            return(kws.Where(x => !string.IsNullOrEmpty(x.GetTrimed()))
                   .Distinct().Select(x => x.GetUrlEncodedString("utf-8"))
                   .Select(x => baiduUrlFormat.FormatStr(x)).ToList());
        }
        public List <level1link> prehandle_data(List <level1link> links, searchkeyword tsk, List <keyword> excludedKeywords)
        {
            if (links == null || links.Count == 0)
            {
                log("BLOCKED " + tsk.Keyword);
                return(links);
            }
            else
            {
                links = links.DistinctBy(x => x.LinkUrl);
                log(links.Count + " Level 1 Links for " + tsk.Keyword);
            }

            //var itm = MySqlDbHelper.GetEfEntities<protectitem>(ctx,"Id="+tsk.ProtectItemId).FirstOrDefault();
            ////{ScoredKeywords:{aaa:12,bbb:13}}
            //if (itm != null && !string.IsNullOrEmpty(itm.FingerPrints2))
            //{
            //    string[] sks = itm.FingerPrints2.SplitWith("$;");
            //    Dictionary<string, int> scores = new Dictionary<string, int>();
            //    if (sks != null)
            //    {
            //        foreach (var sk in sks)
            //        {
            //            string[] sps = sk.SplitWith(":", ":");
            //            if (sps == null || sps.Length != 2)
            //                continue;
            //            string k = sps[0].GetTrimed();
            //            int? s = sps[1].ExInt();
            //            if (sps[1].IsContains2("-"))
            //                s = -1 * s;
            //            if (string.IsNullOrEmpty(k) || !s.HasValue || scores.ContainsKey(k))
            //                continue;
            //            scores.Add(k, s.Value);
            //        }
            //    }
            //    foreach (var l in links)
            //    {
            //        string txt = string.Format("{0}{1}", l.Title, l.Abstract);
            //        l.Score = scores.Sum(x => txt.IsContain(x.Key) ? x.Value : 0);
            //        l.Title = "[使用了自定义打分]" + l.Title;
            //    }
            //}
            //else if (tsk.ProjectType == (byte)ProjectType.Artical && !string.IsNullOrEmpty(itm.FingerPrints))
            //{
            //    foreach (var l in links)
            //    {
            //        var txt = string.Join("", "{0},{1}".FormatStr(l.Title, l.Abstract).SplitWith(
            //            ";", ",", ";", ".", ",", "。", ";",
            //           "-", " ", "?", "“", "!", "”").Select(x => x.GetTrimed()).Where(x => !string.IsNullOrEmpty(x)));
            //        string[] fps = itm.FingerPrints.SplitWith(",");
            //        l.Score = l.Score / 2 + fps.Where(x => txt.IsContain(x)).Count() * 50 / fps.Length;
            //    }
            //}

            links.ForEach(x =>
            {
                //x.Keywords = tsk.Keyword;

                cleaning(x, excludedKeywords);
            });

            links = links.Where(x => x.DataCleanStatus != (byte)DataCleanStatus.Excluded).ToList();
            return(links);
        }
Example #6
0
        void GetLinks(string link, searchkeyword tsk, keyword businessKeyword, List <keyword> businessKeywords, List <keyword> excludedKeywords)
        {
            BotMng  botmng = BotMng.Instance;
            AppType img    = (AppType)tsk.AppType;

            string[] searchKeywords = tsk.Keyword.GetLower().RemoveSpace().Split(';');

            List <KeywordScore> patterns = businessKeywords.Select(x => new KeywordScore {
                Keyword = x.Txt, Score = x.Score, BizType = x.BizType
            }).ToList();

            string[] bizPatterns = businessKeywords.Select(x => x.Txt).ToArray();
            patterns.Add(new KeywordScore {
                Keyword = tsk.Keyword, Score = 50, BizType = 0
            });

            //List<level1link> result = new List<level1link>();
            int nohist_pages = 0;
            int quried_pages = 0;

            //最多搜索60页
            while (!string.IsNullOrEmpty(link) && quried_pages <= 60)
            {
                log(link);
                var html = get_html(link);
                if (html == null)
                {
                    break;
                }
                var tags = html.SubAfter("content_left").SplitWith("c-container");

                if (tags == null || tags.Length == 0)
                {
                    log("BLOCKED " + tsk.Keyword);
                    break;
                }
                bool nohit = true;
                foreach (var tag in tags)
                {
                    var    a     = tag.SubAfter("h3").SubAfter("a");
                    string title = RemoveInivalidChar(
                        a.RemoveSpace().GetLower().SubBefore("</h3>").GetTxtFromHtml2().RemoveSpace().GetLower());
                    string href = a.GetFirstHref2();


                    string abs    = RemoveInivalidChar(tag.SubAfter("abstract").SubBefore("</div").GetTxtFromHtml2().RemoveSpace().GetLower());
                    string domain = tag.SubLastStringAfter("\"f13").SubBefore("</span").GetTxtFromHtml2();
                    domain = GetDomain(domain);

                    int maxScore = 0;
                    //没有包含需要protect item信息的过滤掉
                    string txt = "{0}{1}".FormatStr(title, abs);
                    if (string.IsNullOrEmpty(txt))
                    {
                        continue;
                    }

                    string realUrl = null, detailHtml = null, abstracts = null;
                    byte   appType = 0;

                    if (!string.IsNullOrWhiteSpace(href))
                    {
                        //Encoding enc = Encoding.UTF8;
                        //detailHtml = HtmlQueryHelper.GetContent(href, 8000, ref enc, out realUrl);
                        var tuplehtml = get_htmlUrl(href);
                        if (tuplehtml != null && !string.IsNullOrEmpty(tuplehtml.Item1))
                        {
                            realUrl = tuplehtml.Item1;
                        }
                        if (tuplehtml != null && !string.IsNullOrEmpty(tuplehtml.Item2))
                        {
                            detailHtml = tuplehtml.Item2;
                        }
                        if (!string.IsNullOrEmpty(realUrl) && string.IsNullOrEmpty(domain))
                        {
                            domain = GetDomain(realUrl);
                        }
                    }
                    if (!string.IsNullOrEmpty(detailHtml) && detailHtml.Contains("document.getElementById(\"link\").click()"))
                    {
                        var gourl = detailHtml.GetFirstHref2();
                        if (!string.IsNullOrEmpty(gourl))
                        {
                            var tuplehtml = get_htmlUrl(gourl);
                            if (tuplehtml != null && !string.IsNullOrEmpty(tuplehtml.Item1))
                            {
                                realUrl = tuplehtml.Item1;
                            }
                            if (tuplehtml != null && !string.IsNullOrEmpty(tuplehtml.Item2))
                            {
                                detailHtml = tuplehtml.Item2;
                            }
                            if (!string.IsNullOrEmpty(realUrl) && string.IsNullOrEmpty(domain))
                            {
                                domain = GetDomain(realUrl);
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(realUrl))
                    {
                        realUrl = href;
                    }
                    List <KeywordScore> matchpatterns = new List <KeywordScore>();
                    if (string.IsNullOrEmpty(detailHtml))
                    {
                        continue;
                    }
                    else
                    {
                        if (!detailHtml.Contains(tsk.Keyword) || !detailHtml.IsContains2(bizPatterns))
                        {
                            continue;
                        }
                        var           hrefs          = detailHtml.GetDescendents("a", "href");
                        StringBuilder sbabstracts    = new StringBuilder();
                        List <string> abstractlist   = new List <string>();
                        StringBuilder sbabstractlist = new StringBuilder();

                        foreach (KeywordScore pattern in patterns)
                        {
                            string[] splitDetailHtmls = detailHtml.SplitWith(pattern.Keyword);
                            if (splitDetailHtmls.Length > 1)
                            {
                                matchpatterns.Add(pattern);
                            }
                            StringBuilder sbpatternStr = new StringBuilder();
                            for (int i = 0; i < splitDetailHtmls.Length - 1; i++)
                            {
                                string splitDetailHtml1 = splitDetailHtmls[i];
                                string splitDetailHtml2 = i < splitDetailHtmls.Length - 2 ? splitDetailHtmls[i + 1] : "";
                                for (int j = splitDetailHtml1.Length - 1; j >= 0; j--)
                                {
                                    if (split_bef_commas.Contains(splitDetailHtml1[j]) && j - 1 >= 0 && !split_num_commas.Contains(splitDetailHtml1[j - 1]))
                                    {
                                        break;
                                    }
                                    sbpatternStr.Append(splitDetailHtml1[j]);
                                }
                                for (int q = sbpatternStr.Length - 1; q >= 0; q--)
                                {
                                    sbabstracts.Append(sbpatternStr[q]);
                                }
                                sbabstracts.Append(pattern.Keyword);
                                sbpatternStr.Clear();
                                for (int j = 0; j < splitDetailHtml2.Length; j++)
                                {
                                    if (split_aft_commas.Contains(splitDetailHtml2[j]) && j + 1 < splitDetailHtml2.Length && !split_num_commas.Contains(splitDetailHtml2[j + 1]))
                                    {
                                        break;
                                    }
                                    sbpatternStr.Append(splitDetailHtml2[j]);
                                }
                                sbabstracts.Append(sbpatternStr);
                                sbpatternStr.Clear();

                                string tmpsbabstracts = sbabstracts.ToString();
                                tmpsbabstracts = BaiduQuery.RemoveInivalidChar(tmpsbabstracts.GetTxtFromHtml2().RemoveSpace().GetLower());
                                if (!abstractlist.Contains(tmpsbabstracts))
                                {
                                    abstractlist.Add(tmpsbabstracts);
                                    sbabstractlist.Append(tmpsbabstracts).Append(" ");
                                }
                                sbabstracts.Clear();
                            }
                        }
                        abstracts = sbabstractlist.ToString();
                        if (!string.IsNullOrEmpty(abstracts) && matchpatterns.Count > 0)
                        {
                            maxScore  = matchpatterns.Max(x => x.Score ?? 50);
                            appType   = matchpatterns.Where(x => x.BizType > 0).OrderByDescending(x => x.Score).Select(x => x.BizType).FirstOrDefault();
                            maxScore += matchpatterns.Sum(x => (x.Score ?? 50) / 10);
                            maxScore -= matchpatterns.Max(x => (x.Score ?? 50) / 10);
                        }
                    }
                    if (string.IsNullOrEmpty(abstracts) && !string.IsNullOrEmpty(abs))
                    {
                        matchpatterns = patterns.Where(x => abs.Contains(x.Keyword)).ToList();
                        maxScore      = matchpatterns.Max(x => x.Score ?? 50);
                        appType       = matchpatterns.Where(x => x.BizType > 0).OrderByDescending(x => x.Score).Select(x => x.BizType).FirstOrDefault();

                        maxScore += matchpatterns.Sum(x => (x.Score ?? 50) / 10);
                        maxScore -= matchpatterns.Max(x => (x.Score ?? 50) / 10);
                    }
                    if (maxScore > 100)
                    {
                        maxScore = 100;
                    }

                    bool is_bus_matched = txt.IsContains2(businessKeyword.Txt);

                    bool          is_title_matched = title.GetLower().IsContains2(searchKeywords);
                    bool          is_abstr_matched = abs.IsContains2(searchKeywords);
                    BaiduItemPart part             = is_title_matched && is_abstr_matched ? BaiduItemPart.TitleAbstract :
                                                     is_title_matched ? BaiduItemPart.Title :
                                                     is_abstr_matched ? BaiduItemPart.Abstract : BaiduItemPart.None;
                    bool is_itm_title_matched = txt.GetLower().IsContains2(searchKeywords);



                    level1link l1 = new level1link
                    {
                        UsrId           = tsk.UsrId,
                        Domain          = domain,
                        TopDomain       = GetLevel1Domain(domain),
                        Keywords        = string.Format("{0} + {1}", tsk.Keyword, businessKeyword.Txt),
                        LinkUrl         = realUrl,
                        MatchAt         = (byte)part,
                        Html            = detailHtml,
                        MatchType       = (byte)((is_bus_matched ? 1 : 0) + (is_itm_title_matched ? 2 : 0)),
                        AppType         = appType,
                        BizId           = IDHelper.GetGuid("{0}/{1}/{2}".FormatStr(realUrl, tsk.UsrId, tsk.Keyword)),
                        SearchkeywordId = tsk._id.ToString(),
                        CreatedAt       = DateTime.UtcNow.AddHours(8),
                        Description     = abs,
                        Title           = title,
                        Score           = maxScore,
                        Abstract        = abstracts
                    };

                    byte MatchType = (byte)((is_bus_matched ? 10 : 0) + (is_itm_title_matched ? 30 : 0));

                    botmng.save_level1_links(new List <level1link> {
                        l1
                    }, tsk, excludedKeywords);
                    nohit        = false;
                    nohist_pages = 0;
                }

                if (nohit)
                {
                    nohist_pages++;
                }
                //如果连续3页都没有结果,就跳出
                if (nohist_pages > 3)
                {
                    break;
                }

                quried_pages++;
                pages++;
                link = html.SubAfter("fkfk_cur").SubBefore("下一页").GetLastHref2();
                if (!string.IsNullOrEmpty(link) && !link.IsStartWith("http"))
                {
                    if (link.IsStartWith("/"))
                    {
                        link = link.SubAfter("/");
                    }
                    link = "http://www.baidu.com/".GetContact(link);
                }
            }
            //return result;
        }