private static void HandleCreate(HtmlDocument htmlDoc, HtmlNode row) { try { if (row.InnerHtml.Contains("href")) { string situacao; string quoteLink = row.ChildNodes[3].ChildNodes["a"].Attributes["href"].Value.ToString(); HtmlDocument htmlQuote = WebHandle.GetHtmlDocOfPage(string.Format(Constants.CN_COTACAO_LINK, quoteLink), Encoding.GetEncoding("ISO-8859-1")); Licitacao l = CreateQuote(htmlQuote, quoteLink, out situacao); //RandomSleep(); if (l != null && !repo.Exists(l.IdLicitacaoFonte.ToString())) { repo.Insert(l); numCotacoes++; RService.Log("Cotação " + l.IdLicitacaoFonte + " inserida com sucesso" + " at {0}", Path.GetTempPath() + Name + ".txt"); //SegmentarCotacao(l); } else if (l != null && repo.Exists(l.IdLicitacaoFonte.ToString()) && LicitacaoController.SituacaoAlterada(l.IdLicitacaoFonte.ToString(), situacao)) { l = repo.GetByIdLicitacaoFonte(l.IdLicitacaoFonte.ToString()); l.Situacao = situacao; repo.Update(l); } } } catch (Exception e) { RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } }
/*Cria os objetos Licitacao, Lote e LicitacaoArquivo fazendo as verificações necessárias.*/ private static void HandleCreate(HtmlDocument htmlDoc, string ocnum, string situacao) { try { Regex regex = new Regex("\\d{4}OC"); string ocn = ocnum; ocnum = "1" + regex.Replace(ocnum, DateTime.Now.ToString("yy")); /*Verifica se a oc já não esta na base de dados, cria um novo lote se for preciso*/ //if (!string.IsNullOrEmpty(ocnum) && !AlreadyInserted.Contains(long.Parse(ocnum)) && AguardandoPropostasEditalPub(htmlDoc) && !AlreadyColected.Contains(long.Parse(ocnum))) if (!string.IsNullOrEmpty(ocn) && !LicitacaoController.ExistsBEC(ocn)) { //AlreadyColected.Add(long.Parse(ocnum)); //Preenche os dados da licitação e retorna para inserir na lista Licitacao licitacao = CreateLicitacao(htmlDoc, ocnum, situacao); if (licitacao != null && !string.IsNullOrEmpty(licitacao.LinkEdital)) { licitacao.Observacoes = ocn; Repo.Insert(licitacao); //licitacoes.Add(licitacao); HtmlDocument htmlEditais = WebHandle.GetHtmlDocOfPage(licitacao.LinkEdital); int numeroArquivo = 2; //Faz o download de todos os arquivos do edital foreach (HtmlNode editais in htmlEditais.DocumentNode.Descendants("a").Where(x => x.Attributes.Contains("href") && x.Attributes["href"].Value.Contains("ctl00$conteudo$WUC_Documento1$dgDocumento"))) { DownloadEditais(licitacao.LinkEdital, GetFormParametersEdital(htmlEditais, numeroArquivo)); } CreateLicitacaoArquivo(licitacao); NumLicitacoes++; } else { RService.Log("Exception (HandleCreate) " + Name + ": A licitação não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } else if (!string.IsNullOrEmpty(ocn) && LicitacaoController.ExistsBEC(ocn) && LicitacaoController.SituacaoAlteradaBEC(ocn, situacao)) { int id = LicitacaoController.GetIdByObservacoes(ocn); LicitacaoController.UpdateSituacaoByIdLicitacao(id, situacao); } } catch (Exception e) { RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } }
/*Cria os objetos Licitacao, Lote e LicitacaoArquivo fazendo as verificações necessárias.*/ private static void HandleCreate(HtmlDocument htmlDoc, string ocnum, string situacao) { try { Regex regex = new Regex("\\d{4}OC"); string ocn = ocnum; ocnum = "1" + regex.Replace(ocnum, DateTime.Now.ToString("yy")); //Criar um novo lote se for preciso, verifica o status da oc e também se já esta salva no bd if (!string.IsNullOrEmpty(ocn) && !LicitacaoController.ExistsBEC(ocn)) { //Preenche os dados da licitação e retorna para inserir na lista Licitacao licitacao = CreateLicitacao(htmlDoc, ocnum, situacao); if (licitacao != null && LicitacaoController.IsValid(licitacao, out mensagemErro)) { licitacao.Observacoes = ocn; licitacao.LinkEdital = href.Replace("OC_Item", "Edital"); Repo = new LicitacaoRepository(); Repo.Insert(licitacao); //licitacoes.Add(licitacao); RService.Log("(HandleCreate) " + Name + ": inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); CreateLicitacaoArquivo(licitacao, licitacao.LinkEdital); NumLicitacoes++; } else { RService.Log("Exception (HandleCreate) " + Name + ": A licitação não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } else if (!string.IsNullOrEmpty(ocn) && LicitacaoController.ExistsBEC(ocn) && LicitacaoController.SituacaoAlteradaBEC(ocn, situacao)) { int id = LicitacaoController.GetIdByObservacoes(ocn); LicitacaoController.UpdateSituacaoByIdLicitacao(id, situacao); } } catch (Exception e) { RService.Log("Exception (HandleCreate)" + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } }
private static void HandleCreate(HtmlNode lic) { try { string link = string.Format(Constants.TCMCE_HOST + lic.ChildNodes[1].ChildNodes[0].GetAttributeValue("href", "").ToString()); string[] licParts = link.Split('/'); string licNum = licParts[7] + licParts[9]; HtmlDocument licPage = WebHandle.GetHtmlDocOfPage(link, Encoding.GetEncoding("UTF-8")); string situacao = Regex.Replace(StringHandle.GetMatches(licPage.DocumentNode.InnerHtml, @"Situação:( *)<b>(.*)</b")[0].ToString(), @"Situação:|<b>|</b", "").Trim(); if (!string.IsNullOrEmpty(licNum) && !LicitacaoController.Exists(licNum)) { Licitacao l = CreateLicitacao(licPage, link, licNum, situacao); if (l != null) { repo = new LicitacaoRepository(); repo.Insert(l); RService.Log("(HandleCreate) " + Name + ": Licitação nº" + licNum + " inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); NumLicitacoes++; GetEditalAndArquivos(licPage, l); } else { RService.Log("Exception (HandleCreate) " + Name + ": Licitação não salva. Motivo: " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } else if (!string.IsNullOrEmpty(licNum) && LicitacaoController.Exists(licNum) && LicitacaoController.SituacaoAlterada(licNum, situacao)) { Licitacao licitacao = LicitacaoController.GetByIdLicitacaoFonte(licNum); licitacao.Situacao = situacao; repo = new LicitacaoRepository(); repo.Update(licitacao); } } catch (Exception e) { RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } }
/*Cria os objetos Licitacao, Lote e LicitacaoArquivo*/ private static void HandleCreate(HtmlDocument htmlDocument) { try { string linkEdital = Constants.CMG_SITE + Constants.CMG_LINK_EDITAL + htmlDocument.DocumentNode.Descendants("a").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("arquivoDoEdital")).Attributes["href"].Value; /*Verifica se o pregão já não esta na base de dados*/ if (!string.IsNullOrEmpty(Id) && !LicitacaoController.Exists(Id)) { Licitacao licitacao = CreateLicitacao(htmlDocument, linkEdital); if (licitacao != null) { Repo.Insert(licitacao); RService.Log("(HandleCreate) " + Name + ": Licitação " + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); CreateLicitacaoArquivo(licitacao, linkEdital); //SegmentarLicitacao(licitacao); NumLicitacoes++; } else { RService.Log("Exception (HandleCreate) " + Name + ": A licitação não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } else if (!string.IsNullOrEmpty(Id) && LicitacaoController.Exists(Id) && LicitacaoController.SituacaoAlterada(Id, Situacao)) { Licitacao licitacao = LicitacaoController.GetByIdLicitacaoFonte(Id); licitacao.Situacao = Situacao; LicitacaoRepository repo = new LicitacaoRepository(); repo.Update(licitacao); } } catch (Exception e) { RService.Log("Exception (HandleCreate)" + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } }
/*Metodo que inicia o processamento de dados*/ private static void Init() { RService.Log("(Init) " + Name + ": Começando o processamento... " + "at {0}", Path.GetTempPath() + Name + ".txt"); try { Repo = new LicitacaoRepository(); /*Realiza a atualização das situações das licitações já inseridas*/ //UpdateLicitacoes(); /*Inicia listas e dictionary's com informações necessárias*/ NameToOrgao = OrgaoController.GetNomeUfToOrgao(); NameToModalidade = ModalidadeController.GetNameToModalidade(); UfToCapital = CityUtil.GetUfToCapital(); UfToNomeCidadeToIdCidade = CidadeController.GetUfToNameCidadeToIdCidade(); Lote = LoteController.CreateLote(43, IdFonte); TryReload = true; if (DoSearch()) { /*Percorre cada licitação encontrada*/ foreach (var numUf in numUFs) { /*Acessa a página da licitação*/ try { if (!LicitacaoController.Exists(numUf.Split(':')[0])) { /*Cria o objeto licitação com as informações da página*/ Licitacao licitacao = CreateLicitacao(numUf); if (licitacao != null) { Repo.Insert(licitacao); NumLicitacoes++; RService.Log("(Init) " + Name + ": Licitação inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); /*Segmenta a licitação recém criada*/ //SegmentarLicitacao(licitacao); DownloadEdAndCreatLicArq(licitacao); } else { if (licitacao != null && licitacao.Orgao != null) { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + licitacao.Num + " e órgão " + licitacao.Orgao.Nome + " - " + licitacao.Orgao.Estado + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } else { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + numUf.Split(':')[0] + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } } } catch (Exception e) { RService.Log("Exception (Init - CreateLicitacao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } } } } catch (Exception e) { RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } }
/*Cria uma nova licitacao e o lote se for necessário*/ public static bool CreateLicitacao() { try { string entidadeExecutora = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnmExecutor")).GetAttribute("value"); string objeto = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdsObjeto")).GetAttribute("value"); string numLicitacao = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnrProcessoEdital")).GetAttribute("value"); string preco = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbvlReferencia")).GetAttribute("value"); string dotacao = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnrDotacaoOrcamentaria")).GetAttribute("value"); string modalidade = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdsModalidadeLicitacao")).GetAttribute("value"); string numProcesso = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbnrEditalOrigem")).GetAttribute("value"); string dataLancamento = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdtLancamentoPublicacao")).GetAttribute("value"); string precoMax = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbvlReferencia")).GetAttribute("value"); string dataAberturaEntrega = ""; if (CidadeAtual == "Diamante do Oeste") { CidadeAtual = "Diamante d'Oeste"; } if (Regex.IsMatch(web.PageSource, @"ctl00_ContentPlaceHolder1_tbdtAberturaLicitacao", RegexOptions.IgnoreCase)) { dataAberturaEntrega = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdtAberturaLicitacao")).GetAttribute("value"); //Caso a licitação tenha o campo NOVA Data Abertura preenchido if (Regex.IsMatch(web.PageSource, @"ctl00_ContentPlaceHolder1_tbdtAberturaNova", RegexOptions.IgnoreCase)) { string dataNovaAberturaEntrega = web.FindElement(By.Id("ctl00_ContentPlaceHolder1_tbdtAberturaNova")).GetAttribute("value"); if (!string.IsNullOrEmpty(dataNovaAberturaEntrega)) { dataAberturaEntrega = dataNovaAberturaEntrega; } } string cod = GenerateCod(entidadeExecutora, dataLancamento, numProcesso, preco); string scod = cod.ToString().Substring(0, 19); long numLong = 0; long numScod = long.TryParse(scod, out numLong) ? numLong : 0; if (!string.IsNullOrEmpty(scod) && !LicitacaoController.Exists(scod)) { if (!LicitacaoController.Exists(objeto, preco, "Dotação Orçamentária: " + dotacao, numLicitacao, numProcesso, Constants.TCEPR_HOST)) { RService.Log("(CreateLicitacao) " + Name + ": Criando licitação num... " + scod + " at {0}", Path.GetTempPath() + Name + ".txt"); Licitacao licitacao = new Licitacao(); licitacao.Objeto = objeto; licitacao.Processo = numProcesso; licitacao.IdLicitacaoFonte = numScod; licitacao.IdFonte = 510; licitacao.Excluido = 0; licitacao.SegmentoAguardandoEdital = 0; licitacao.DigitacaoUsuario = 43; //Robo licitacao.Lote = Lote; //licitacao.DigitacaoData = null; //licitacao.ProcessamentoData = null; licitacao.Observacoes = "Dotação Orçamentária: " + dotacao + " / Data de lançamento do edital pela entidade executora: " + dataLancamento; licitacao.LinkSite = Constants.TCEPR_HOST; licitacao.Cidade = CidadeAtual; licitacao.CidadeFonte = CidadeController.GetIdCidade(CidadeAtual, Constants.TCEPR_UF); licitacao.EstadoFonte = Constants.TCEPR_UF; licitacao.Estado = Constants.TCEPR_ESTADO; licitacao.Modalidade = NameToModalidade.ContainsKey(StringHandle.RemoveAccent(modalidade).ToUpper()) ? NameToModalidade[StringHandle.RemoveAccent(modalidade).ToUpper()] : null; licitacao.Num = numLicitacao; licitacao.AberturaData = DateHandle.Parse(dataAberturaEntrega, "dd/MM/yyyy"); licitacao.EntregaData = DateHandle.Parse(dataAberturaEntrega, "dd/MM/yyyy"); licitacao.ValorMax = precoMax; licitacao.Orgao = OrgaoController.GetOrgaoByNameAndUf(entidadeExecutora.Trim() + ":PR", NameToOrgao); if (LicitacaoController.IsValid(licitacao, out mensagemErro)) { Repo.Insert(licitacao); //licitacoes.Add(licitacao); RService.Log("Licitacao salva com sucesso at {0}", Path.GetTempPath() + Name + ".txt"); TotalLic++; } else { if (licitacao.Orgao != null) { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + licitacao.Num + " e órgão " + licitacao.Orgao.Nome + " - " + licitacao.Orgao.Estado + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } else { RService.Log("Exception (CreateLicitacao) " + Name + ": A licitação de nº " + licitacao.Num + " não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt"); } } } } } } catch (Exception e) { RService.Log("Exception (CreateLicitacao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt"); } return(true); }
private static void Navigate() { int licitIndex = 0, rowCount = 0; try { do { web.Navigate().GoToUrl(Constants.CRJ_HOST); //para obter o cookie do portal if (licitIndex == 0) { RService.Log("(Navigate) " + Name + ": Acessando as licitações do dia... at {0}", LogPath); } web.FindElementById("pesquisarLicitacoesFuturas").Click(); Thread.Sleep(3000); var select = new SelectElement(web.FindElementByName("dataTable_length")); select.SelectByIndex(4); Thread.Sleep(8000); var rowArray = web.FindElements(By.TagName("tr")).Where(x => x.GetAttribute("class") == "odd" || x.GetAttribute("class") == "even").ToArray(); rowCount = rowArray.Count(); if (licitIndex == 0) { RService.Log("(Navigate) " + Name + ": Encontradas " + rowCount + " licitações hoje at {0}", LogPath); } web.FindElements(By.TagName("tr")) .Where(x => x.GetAttribute("class") == "odd" || x.GetAttribute("class") == "even") .ToArray()[licitIndex].Click(); Licitacao licitacao = GetLicitacao(); if (licitacao != null && !repo.Exists(licitacao.IdLicitacaoFonte.ToString())) { repo.Insert(licitacao); NumLicitacoes++; RService.Log("(GetLicitacoes) " + Name + ": Licitação " + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", LogPath); GetFiles(licitacao); } else { RService.Log("Exception (GetLicitacoes) " + Name + ": Licitação não inserida. Motivo(s): " + (string.IsNullOrEmpty(mensagemErro) ? "Licitação já inserida" : mensagemErro) + " at {0}", LogPath); } licitIndex++; } while (licitIndex < rowCount && rowCount != 0); } catch (Exception e) { RService.Log("Exception (Navigate): " + e.Message + " / " + e.StackTrace + " at {0}", LogPath); } }
private static void HandleLicitacoes(int index) { RService.Log("(HandleLicitacoes) " + name + ": Consultando licitações da " + Constants.TCESE_MUN_NAME[index] + " at {0}", logPath); //LoadWebDriver(); LoadDriver(); try { string urlMunicipio = string.Format(Constants.TCESE_MUN_PAGE, Constants.TCESE_MUN_CODE[index], Constants.TCESE_MUN_NAME[index].Replace(" ", "%20")); temLicitacao = false; web.Navigate().GoToUrl(urlMunicipio); var licits = web.FindElements(By.TagName("a")).Where(x => x.GetAttribute("innerText").Contains("Ano/Número:")); repo = new LicitacaoRepository(); foreach (var licit in licits) { var dates = StringHandle.GetMatches(licit.Text, @"\d+/\d+/\d+"); if (Convert.ToDateTime(dates[0].Value) > DateTime.Today) { temLicitacao = true; var licitLink = licit.GetAttribute("href"); Licitacao licitacao = CreateLicitacao(licitLink, index); if (licitacao != null) { if (!LicitacaoController.Exists(licitacao.IdLicitacaoFonte.ToString())) { repo.Insert(licitacao); //licitacoes.Add(licitacao); RService.Log("(HandleLicitacoes) " + name + ": Licitação Nº" + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", logPath); numLicitacoes++; } } else { RService.Log("Exception (CreateLicitacao) " + name + ": Licitação não salva. Motivo: " + mensagemErro + " at {0}", logPath); } } } if (!temLicitacao) { RService.Log("(HandleLicitacoes) " + name + ": " + Constants.TCESE_MUN_NAME[index] + " não possui licitações novas at {0}", logPath); } } catch (Exception e) { RService.Log("Exception (HandleLicitacoes) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", logPath); } finally { if (web != null) { web.Close(); } } }
private static void GetLicitacoes(List <string> licitLinks) { foreach (var link in licitLinks) { try { if (web != null) { web.Quit(); } var driver = ChromeDriverService.CreateDefaultService(); driver.HideCommandPromptWindow = true; var op = new ChromeOptions(); op.AddUserProfilePreference("download.default_directory", PathEditais); web = new ChromeDriver(driver, new ChromeOptions(), TimeSpan.FromSeconds(300)); web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); wait = new WebDriverWait(web, TimeSpan.FromSeconds(300)); web.Navigate().GoToUrl(link); CheckReCaptcha(web.PageSource); var situacao = web.FindElement(By.XPath("//*[@id=\"report_38717872527149671_catch\"]/dl/dd[4]")).Text; var andamento = web.FindElement(By.XPath("//*[@id=\"L38976648273068799\"]/div/span[2]")); if (!situacao.Contains("Encerrada") || !andamento.Text.Contains("Ativo")) { Licitacao licitacao = CreateLicitacao(link, situacao); try { if (LicitacaoController.IsValid(licitacao, out mensagemErro) && !LicitacaoController.ExistsTCERS(licitacao.IdLicitacaoFonte, Constants.TCERS_ID_FONTE) /*!AlreadyInserted.Contains(licitacao.IdLicitacaoFonte)*/) { repo.Insert(licitacao); NumLicitacoes++; RService.Log("(GetLicitacoes) " + Name + ": Licitação nº" + licitacao.Num + " salva com sucesso at {0}", LogPath); //GetArquivos(licitacao); } else if (!string.IsNullOrEmpty(mensagemErro)) { RService.Log("Exception (GetLicitacoes - Insert) " + Name + ": " + mensagemErro + " at {0}", LogPath); } else { RService.Log("Exception (GetLicitacoes - Insert) " + Name + ": Licitação já capturada anteriormente at {0}", LogPath); } } catch (Exception e) { RService.Log("Exception (GetLicitacoes - Insert) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath); } } } catch (Exception e) { if (web.FindElement(By.Id("g-recaptcha-response")) != null) { RService.Log("Exception (GetLicitacoes) " + Name + ": Encontrado recaptcha! at {0}", LogPath); } RService.Log("Exception (GetLicitacoes) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath); } } }
//Método para pegar as licitações do site do TCE-PI private static void GetLicitacoes() { try { //var webdriver = WebDriverChrome.LoadWebDriver(name); //var webdriver = WebDriverPhantomJS.LoadWebDriver(name, web); //web = webdriver.Item1; //wait = webdriver.Item2; if (web != null) { web.Quit(); } var driver = ChromeDriverService.CreateDefaultService(); driver.HideCommandPromptWindow = true; var op = new ChromeOptions(); op.AddUserProfilePreference("download.default_directory", TCEPIController.pathEditais); web = new ChromeDriver(driver, op, TimeSpan.FromSeconds(300)); web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); wait = new WebDriverWait(web, TimeSpan.FromSeconds(300)); web.Navigate().GoToUrl(Constants.TCEPI_SITE); wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id=\"formMural:btnPesquisar\"]/span[2]"))); web.FindElement(By.XPath("//*[@id=\"formMural:btnPesquisar\"]/span[2]")).Click(); Thread.Sleep(3000); /*Laço que se repete até o fim das licitações. O fim é demarcado pela quantidade de licitações na lista licitNums: * em cada página o número é 50, menos na última página. Quando o número for diferente de 50, ele termina*/ do { licitNums = new List <string>(); RService.Log("(GetLicitacoes) " + name + ": Acessando página " + currentPage + " at {0}", logPath); string pageHtml = web.PageSource.ToString(); var licits = StringHandle.GetMatches(pageHtml, @"\?id=\d{6}"); //Pega os números das licitações da página em questão foreach (var licit in licits) { string licNum = licit.ToString().Replace("?id=", ""); licitNums.Add(licNum); } RService.Log("(GetLicitacoes) " + name + ": Acessando licitações da página " + currentPage + " at {0}", logPath); foreach (string lic in licitNums) { if (!alreadyInserted.Contains(Int64.Parse(lic))) { Licitacao licitacao = CreateLicitacao(lic); if (licitacao != null && !LicitacaoController.Exists(licitacao.IdLicitacaoFonte.ToString())) { repo = new LicitacaoRepository(); try { repo.Insert(licitacao); RService.Log("(GetLicitacoes) " + name + ": Licitação " + licitacao.IdLicitacaoFonte + " inserida com sucesso at {0}", logPath); numLicitacoes++; GetFiles(licitacao); } catch (Exception e) { RService.Log("Exception (GetLicitacoes) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / Mensagem de erro: " + mensagemErro + " at {0}", logPath); } } } } //webdriver = WebDriverChrome.LoadWebDriver(name); //web = webdriver.Item1; //wait = webdriver.Item2; web = new ChromeDriver(driver, op, TimeSpan.FromSeconds(300)); web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); wait = new WebDriverWait(web, TimeSpan.FromSeconds(300)); web.Navigate().GoToUrl(Constants.TCEPI_SITE); web.FindElement(By.XPath("//*[@id=\"formMural:btnPesquisar\"]/span[2]")).Click(); for (int i = 0; i < currentPage; i++) { wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id=\"formListaLic:listaLic_paginator_top\"]/a[3]"))); web.FindElement(By.XPath("//*[@id=\"formListaLic:listaLic_paginator_top\"]/a[3]")).Click(); Thread.Sleep(10000); } currentPage++; } while (licitNums.Count() == 10); } catch (Exception e) { StackTrace st = new StackTrace(e, true); var frame = st.GetFrame(st.FrameCount - 1); var line = frame.GetFileLineNumber(); RService.Log("Exception (GetLicitacoes) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at line " + line + " at {0}", logPath); } }