Пример #1
0
        private CookieContainer GetCookie(string loginPage, string accountNumber, string username, string password)
        {
            string reqString = "AccountNumber=" + accountNumber + "&UserName="******"&Password="******"POST";
                request.ContentType     = "application/x-www-form-urlencoded";
                request.ContentLength   = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                Errors.LoginPageError(ex);
                PB.Close();
            }
            return(cookieContainer);
        }
Пример #2
0
        private CookieContainer GetCookie(string loginPage, string username, string password)
        {
            try
            {
                cd.Url = loginPage;
                IWebElement element;

                element = cd.FindElement(By.Id("_username"));
                element.SendKeys(username);
                element = cd.FindElement(By.Id("_password"));
                element.SendKeys(password);

                element = cd.FindElement(By.XPath("//*[@class = 'btn btn-success']"));
                element.Click();

                foreach (OpenQA.Selenium.Cookie c in cd.Manage().Cookies.AllCookies)
                {
                    string name  = c.Name;
                    string value = c.Value;
                    cookieContainer.Add(new System.Net.Cookie(name, value, c.Path, c.Domain));
                }
                cd.Quit();
            }
            catch (Exception ex)
            {
                cd.Quit();
                PB.Close();
                Errors.LoginPageError(ex);
            }
            return(cookieContainer);
        }
Пример #3
0
        private CookieContainer GetCookie(string loginPage, string accountNumber, string username, string password)
        {
            // Сначала получаем токен:
            request = (HttpWebRequest)WebRequest.Create(loginPage);
            request.CookieContainer = cookieContainer;

            response = (HttpWebResponse)request.GetResponse();
            sr       = new StreamReader(response.GetResponseStream());
            string pageSource = sr.ReadToEnd();

            string searchWord = "name=\"cmsauthenticitytoken\" value=\"";
            string token      = pageSource.Substring(pageSource.IndexOf(searchWord) + searchWord.Length);

            token = token.Remove(token.IndexOf("\""));
            //==================================================================================================

            string reqString =
                "module_fnc%5Bprimary%5D=Login&sSuccessURL=&sFailureURL=&sConsumer=loginBox"
                + "&customerNumber=" + accountNumber
                + "&slogin="******"&password="******"&cmsauthenticitytoken=" + token;

            byte[] data = Encoding.UTF8.GetBytes(reqString);
            try
            {
                request = (HttpWebRequest)WebRequest.Create(loginPage);
                request.CookieContainer = cookieContainer;
                request.Method          = "POST";
                request.ContentType     = "application/x-www-form-urlencoded";
                request.ContentLength   = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                Errors.LoginPageError(ex);
                PB.Close();
            }
            return(cookieContainer);
        }
Пример #4
0
        public BookDepository(string[] isbns)
        {
            string isbnUrl    = "https://www.bookdepository.com/search?searchTerm=";
            string pageSource = string.Empty;
            string temp       = string.Empty;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            try
            {
                for (int i = 0; i < isbns.Length; i++)
                {
                    // Пауза чтобы не нагружать сервер :)
                    Thread.Sleep(2000);

                    // Присваиваем порядковый номер
                    number = (i + 1).ToString();

                    // Присваиваем ISBN
                    isbn = isbns[i].Replace("\n", "");
                    isbn = isbn.Replace("\r", "");

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту BookDepository. Обработано {i + 1} из {isbnsLength}";
                    PB.progressBar.Value++;
                    progressvalue++;
                    Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                    //==================================================================================================

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;
                        request.UserAgent       = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"; // 537.36

                        response   = (HttpWebResponse)request.GetResponse();
                        sr         = new StreamReader(response.GetResponseStream());
                        pageSource = sr.ReadToEnd();
                    }
                    //==================================================================================================

                    // Блок обработки страницы с ответом
                    if (pageSource != string.Empty && isbn != "")
                    {
                        //pageSource = AlphabetCheck.Check(pageSource);

                        // Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
                        // Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
                        temp = "<span itemprop=\"isbn\">";
                        string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                        checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));

                        if (isbn != checkISBN && !pageSource.Contains("Advanced Search"))
                        {
                            isbn2 = "ISBN не совпадает: " + checkISBN;
                        }

                        // Присваиваем наименование
                        temp = "<h1 itemprop=\"name\">";
                        if (pageSource.Contains(temp))
                        {
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Remove(title.IndexOf("<"));
                            title = AlphabetCheck.Check(title);
                        }

                        // Присваиваем автора. Авторов может быть несколько ищем все строки
                        temp = "<div class=\"author-info";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</div>"));

                            string[] rows = temp.Split('\n');

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("itemscope=\""))
                                {
                                    temp    = rows[j].Substring(rows[j].IndexOf("itemscope=\"") + 11);
                                    temp    = temp.Remove(temp.IndexOf("\""));
                                    author += temp + ", ";
                                }
                            }
                            try
                            {
                                author = author.Remove(author.LastIndexOf(","));
                                author = AlphabetCheck.Check(author);
                            }
                            catch
                            {
                                author = string.Empty;
                            }
                        }

                        // Присваиваем дату издания
                        temp = "<span itemprop=\"datePublished\">";
                        if (pageSource.Contains(temp))
                        {
                            pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            pubDate = AlphabetCheck.Check(pubDate);
                        }

                        // Присваиваем издательство
                        temp = "<span itemprop=\"publisher\"";
                        if (pageSource.Contains(temp))
                        {
                            publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            publisher = publisher.Substring(publisher.IndexOf("itemscope=\"") + 11);
                            publisher = publisher.Remove(publisher.IndexOf("\""));
                            publisher = AlphabetCheck.Check(publisher);
                        }

                        // Присваиваем импринт
                        temp = "<label>Imprint</label>";
                        if (pageSource.Contains(temp))
                        {
                            imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imprint = imprint.Substring(imprint.IndexOf(">") + 1);
                            imprint = imprint.Remove(imprint.IndexOf("<"));
                            imprint = AlphabetCheck.Check(imprint);
                        }

                        // Присваиваем цену с валютой и без нее
                        temp = "<span class=\"sale-price\">";
                        if (pageSource.Contains(temp))
                        {
                            priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                            priceWithCurrency = priceWithCurrency.Replace("US$", "") + " USD";
                            priceWithCurrency = priceWithCurrency.Replace(".", ",");
                            price             = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
                        }

                        // Проверяем, есть ли строка, говорящая о недоступности
                        temp = "<p class=\"list-price\">";
                        if (pageSource.Contains(temp))
                        {
                            availability       = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            priceWithCurrency  = availability.Substring(availability.IndexOf("$") + 1);
                            priceWithCurrency  = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                            priceWithCurrency += " USD";
                            priceWithCurrency  = priceWithCurrency.Replace(".", ",");
                            price              = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));

                            availability = availability.Substring(availability.IndexOf(">") + 1);

                            if (availability.Contains("<p class=\"red-text bold\">"))
                            {
                                availability = availability.Substring(availability.IndexOf(">") + 1);
                                availability = availability.Remove(availability.IndexOf("<"));
                            }
                        }

                        // Присваиваем доступность
                        temp = "<div class=\"availability-text\">";
                        if (pageSource.Contains(temp))
                        {
                            availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            availability = availability.Substring(availability.IndexOf("<p>") + 3);
                            availability = availability.Remove(availability.IndexOf("<"));
                            availability = AlphabetCheck.Check(availability);
                        }

                        // Присваиваем вес
                        temp = "<label>Dimensions</label>";
                        if (pageSource.Contains(temp))
                        {
                            try
                            {
                                weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                weight = weight.Remove(weight.IndexOf("</span>"));
                                weight = weight.Substring(weight.IndexOf("| ") + 1);
                                weight = weight.Remove(weight.IndexOf("g"));
                                weight = weight.Replace(",", "");
                                weight = weight.Replace(".", ",");

                                weight = AlphabetCheck.Check(weight);

                                weight = Math.Round((double.Parse(weight)) / 1000, 3).ToString();
                            }
                            catch
                            {
                                weight = string.Empty;
                            }
                        }

                        // Присваиваем размеры
                        temp = "<label>Dimensions</label>";
                        if (pageSource.Contains(temp))
                        {
                            dimensions = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            dimensions = dimensions.Replace("<span>", "");
                            dimensions = dimensions.Remove(dimensions.IndexOf("mm"));
                            dimensions = AlphabetCheck.Check(dimensions);

                            string[] dim = dimensions.Split('x');
                            try
                            {
                                length = Math.Round(double.Parse(dim[1].Replace('.', ','))).ToString();
                                width  = Math.Round(double.Parse(dim[0].Replace('.', ','))).ToString();
                                height = Math.Round(double.Parse(dim[2].Replace('.', ','))).ToString();
                            }
                            catch { }
                        }

                        // Присваиваем страну происхождения
                        temp = "<label>Publication City/Country</label>";
                        if (pageSource.Contains(temp))
                        {
                            pubCountry = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubCountry = pubCountry.Replace("<span>", "");
                            pubCountry = pubCountry.Remove(pubCountry.IndexOf("<"));
                            pubCountry = AlphabetCheck.Check(pubCountry);
                        }

                        // Присваиваем обложку
                        temp = "<label>Format</label>";
                        if (pageSource.Contains(temp))
                        {
                            bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            bookCover = bookCover.Substring(bookCover.IndexOf(">") + 1);
                            bookCover = bookCover.Remove(bookCover.IndexOf("<"));

                            // Здесь может быть ошибка. Т.к. не всегда присутствует элемент " | "
                            try
                            {
                                if (bookCover.IndexOf('|') >= 0)
                                {
                                    bookCover = bookCover.Remove(bookCover.IndexOf("|"));
                                }
                            }
                            catch { }
                            bookCover = AlphabetCheck.Check(bookCover);
                        }

                        // Присваиваем страницы
                        temp = "<span itemprop=\"numberOfPages\">";
                        if (pageSource.Contains(temp))
                        {
                            pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pages = pages.Remove(pages.IndexOf(" "));
                        }

                        // Присваиваем описание
                        temp = "<div class=\"item-excerpt trunc\" itemprop=\"description\" data-height=\"230\">";
                        if (pageSource.Contains(temp))
                        {
                            try
                            {
                                description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                description = description.Remove(description.IndexOf("</div>"));
                                description = description.Remove(description.IndexOf("<a class"));
                                //description = description.Remove(description.LastIndexOf("<br />"));
                                //description = description.Replace("<br />", " ");

                                if (description.StartsWith("-"))
                                {
                                    description = description.Replace("-", "'-");
                                }

                                // Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
                                // Когда нашли индексы убираем содержимое между ними методом Remove
                                if (description.Contains("<a href"))
                                {
                                    bool isContainsLink = true;

                                    while (isContainsLink != false)
                                    {
                                        int startIndex = description.IndexOf("<a href");
                                        int lastIndex  = description.IndexOf(">", startIndex) + 1;
                                        description = description.Remove(startIndex, lastIndex - startIndex);
                                        description = description.Replace("</a>", "");

                                        if (!description.Contains("<a href"))
                                        {
                                            isContainsLink = false;
                                        }
                                    }
                                }
                                description = AlphabetCheck.Check(description);
                            }
                            catch
                            {
                                description = string.Empty;
                            }
                            //==================================================================================================
                        }

                        // Присваиваем ссылку на картинку
                        temp = "<div class=\"item-img-content\">";
                        if (pageSource.Contains(temp))
                        {
                            imageUrl = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imageUrl = imageUrl.Substring(imageUrl.IndexOf("\"") + 1);
                            imageUrl = imageUrl.Remove(imageUrl.IndexOf("\" "));
                        }

                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Пример #5
0
        public PubEasy(string[] isbns)
        {
            string loginPage = "https://beta.pubeasy.com/static/pubeasy/index.html";
            string login     = "******";
            string username  = "******";
            string password  = "******";
            bool   notFound  = false;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            WebDriverWait wait5  = new WebDriverWait(cd, TimeSpan.FromSeconds(5));
            WebDriverWait wait10 = new WebDriverWait(cd, TimeSpan.FromSeconds(10));
            WebDriverWait wait16 = new WebDriverWait(cd, TimeSpan.FromSeconds(16));

            try
            {
                cd.Url = loginPage;
                IWebElement element;

                element = cd.FindElement(By.XPath("//li/a[contains(@href, 'login')]"));
                element.Click();

                // КОД для логина и пароля
                element = cd.FindElement(By.Id("login-id"));
                element.SendKeys(login);
                element = cd.FindElement(By.Id("user-id"));
                element.SendKeys(username);
                element = cd.FindElement(By.Id("login-password"));
                element.SendKeys(password);

                element = cd.FindElement(By.XPath("//input[contains(@type, 'submit')]"));
                element.Click();
                element = cd.FindElement(By.XPath("//a[contains(text(), 'SEARCH NOW >')]"));
                element.Click();

                try
                {
                    for (int i = 0; i < isbns.Length; i++)
                    {
                        // Присваиваем порядковый номер
                        number = (i + 1).ToString();

                        // Присваиваем ISBN
                        isbn = isbns[i].Replace("\n", "");
                        isbn = isbn.Replace("\r", "");

                        // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                        PB.Title = $"Поиск по сайту PubEasy. Обработано {i + 1} из {isbnsLength}";
                        PB.progressBar.Value++;
                        progressvalue++;
                        Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                              new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                        //==================================================================================================


                        if (isbn != string.Empty)
                        {
                            // Переключаем драйвер на первую вкладку браузера
                            cd.SwitchTo().Window(cd.WindowHandles.First());

                            element = cd.FindElement(By.XPath("//*[@id = 'search']/input"));
                            element.Clear();
                            element.SendKeys(isbn);
                            element.SendKeys(Keys.Enter);

                            try
                            {
                                // КОД для определения нашлась ли искомая позиция
                                element  = cd.FindElement(By.XPath("//strong[contains(text(), 'No records found')]"));
                                notFound = true;
                                cd.Navigate().Back();
                            }
                            catch { }

                            if (notFound != true)
                            {
                                try // Поиск наименования
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']//a[2]/font"));
                                    title   = element.Text;
                                    title   = title.Replace("\n", " ");
                                    title   = title.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск автора
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[2]"));
                                    author  = element.Text;
                                }
                                catch { }

                                try // Поиск даты издания
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[6]"));
                                    pubDate = element.Text;
                                    pubDate = pubDate.Replace("\n", " ");
                                    pubDate = pubDate.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск издательства
                                {
                                    element   = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[4]"));
                                    publisher = element.Text;
                                }
                                catch { }

                                try // Поиск поставщика
                                {
                                    element  = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[5]"));
                                    supplier = element.Text;
                                }
                                catch { }

                                try // Поиск цены
                                {
                                    element           = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[7]"));
                                    priceWithCurrency = element.Text;
                                    priceWithCurrency = priceWithCurrency.Replace("\r", " ");
                                    priceWithCurrency = priceWithCurrency.Replace("\n", " ");
                                    priceWithCurrency = priceWithCurrency.Replace(" (Retail)", "");
                                    priceWithCurrency = priceWithCurrency.Replace(" (List)", "");
                                    price             = priceWithCurrency.Replace(" GBP", "");
                                    price             = price.Replace(".", ",");
                                }
                                catch { }

                                try // Поиск доступности
                                {
                                    element      = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[8]"));
                                    availability = element.Text;
                                    availability = availability.Replace("\n", " ");
                                    availability = availability.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск обложки
                                {
                                    element   = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[3]"));
                                    bookCover = element.Text;
                                }
                                catch { }

                                if (supplier.StartsWith("bertram", StringComparison.OrdinalIgnoreCase) |
                                    supplier.StartsWith("gardners", StringComparison.OrdinalIgnoreCase))
                                {
                                    ClearBookList();
                                }

                                try
                                {
                                    // Пытаемся перейти по ссылке Availability ==========
                                    element = cd.FindElement(By.XPath("//*[@class = 'odd']/td[8]/a"));
                                    element.Click();
                                    // ==================================================

                                    try
                                    {
                                        cd.SwitchTo().Window(cd.WindowHandles.Last());

                                        element = cd.FindElement(By.XPath("//iframe[@class = 'embed-responsive-item']"));
                                        cd.SwitchTo().Frame(element);

                                        wait16.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath("//*[@class = 'table-responsive']/table/tbody/tr[6]/td[2]")));

                                        //Меняем наименование ===============================
                                        title = cd.FindElement(By.XPath("//*[@class = 'table-responsive']/table/tbody/tr/td[2]")).Text;
                                        // ==================================================

                                        //Проверка соответсвия цены =========================

                                        try
                                        {
                                            element          = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Price')]]/td[2]"));
                                            priceComparision = element.Text;
                                            priceComparision = priceComparision.Replace("\r\n", " ");
                                            priceComparision = priceComparision.Replace(" (Retail)", "");
                                            priceComparision = priceComparision.Replace("(Retail)", "");
                                            priceComparision = priceComparision.Replace(" (British Pounds)", "");
                                            priceComparision = priceComparision.Replace("(British Pounds)", "");
                                            priceComparision = priceComparision.Replace(" (List)", "");
                                            priceComparision = priceComparision.Replace("(List)", "");
                                            priceComparision = priceComparision.Replace(" GBP", "");
                                            priceComparision = priceComparision.Replace(".", ",");
                                            priceComparision = priceComparision.Replace("Not applicable", "");

                                            if (price == priceComparision)
                                            {
                                                priceComparision = string.Empty;
                                            }
                                        }
                                        catch { }
                                        // ==================================================

                                        //Поиск скидки ==========================================
                                        try
                                        {
                                            element  = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Base Discount')]]/td[2]"));
                                            discount = element.Text;
                                            discount = discount.Replace("%", "");
                                            discount = discount.Replace(".", ",");
                                        }
                                        catch { }
                                        // ==================================================

                                        // Market Restrictions ==============================
                                        try
                                        {
                                            element            = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Market Restrictions')]]/td[2]"));
                                            marketRestrictions = element.Text;
                                        }
                                        catch { }
                                        // ==================================================

                                        // Availability со второй страницы ==================
                                        try
                                        {
                                            element       = cd.FindElement(By.XPath("//tr[@valign = 'TOP' and .//td[contains(text(), 'Availability')]]/td[2]"));
                                            availability2 = element.Text;
                                            availability2 = availability2.Replace("\n", "");
                                            availability2 = availability2.Replace("\r", "");
                                        }
                                        catch { }
                                        // ==================================================

                                        cd.Close();
                                    }
                                    catch
                                    {
                                        priceComparision = "Страница не загрузилась.";
                                        cd.Close();
                                    }
                                }
                                catch
                                { }
                            }
                            notFound = false;
                            AddBookToList();
                            ClearBookList();
                        }
                    }
                }
                catch (Exception ex)
                {
                    cd.Quit();
                    PB.Close();
                    Errors.CustomError(ex);
                }
                cd.Quit();
                PB.Close();
                WorkWithFile.SaveFile(book);
            }
            catch (Exception ex)
            {
                cd.Quit();
                PB.Close();
                Errors.LoginPageError(ex);
            }
        }
Пример #6
0
        public ABEIPS(string[] isbns)
        {
            string loginPage = "https://biznes.abe.pl/login";
            string isbnUrl   = "https://biznes.abe.pl/search/?search_param=all&q=";
            string username  = "******";
            string password  = "******";

            string pageSource = string.Empty;
            string temp       = string.Empty;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            var cookieContainer = GetCookie(loginPage, username, password);

            try
            {
                for (int i = 0; i < isbns.Length; i++)
                {
                    // Пауза чтобы не нагружать сервер :)
                    Thread.Sleep(1000);

                    // Присваиваем порядковый номер
                    number = (i + 1).ToString();

                    // Присваиваем ISBN
                    isbn = isbns[i].Replace("\n", "");
                    isbn = isbn.Replace("\r", "");

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту ABE-IPS. Обработано {i + 1} из {isbnsLength}";
                    PB.progressBar.Value++;
                    progressvalue++;
                    Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                    //==================================================================================================

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница со списком, которую мы записываем в переменную PageSource
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;

                        response   = (HttpWebResponse)request.GetResponse();
                        sr         = new StreamReader(response.GetResponseStream());
                        pageSource = sr.ReadToEnd();
                    }
                    //==================================================================================================

                    // Проверка, удалось ли залогиниться, если на сранице есть текст "Login" значит прерываем цикл.
                    if (pageSource.Contains("Login"))
                    {
                        MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
                        break;
                    }
                    //==================================================================================================

                    // Блок обработки страницы с результатом первого запроса.
                    // Так как на странице с результатом может быть несколько ссылок на книги, пробуем найти нужную нам.
                    // Найденную ссылку передаем в следующий запрос

                    string delimeter = "<div class=\"col-md-6\">";

                    if (pageSource.Contains(delimeter))
                    {
                        // Разбиваем текст страницы на строки и считаем сколько строк содержит наш delimeter
                        // Это нужно чтобы создать массив с нужными нам элементами
                        string[] rows     = pageSource.Split('\n');
                        int      divCount = 0;

                        for (int j = 0; j < rows.Length; j++)
                        {
                            if (rows[j].Contains(delimeter))
                            {
                                divCount++;
                            }
                        }

                        // Собираем все строки содержащие delimeter в массив divs,
                        // в них нужно найти ту строку в которой упоминается ISBN нашей книги.
                        // Правильная строка обрабатывается и присваивается переменной href.
                        string[] div = new string[divCount];

                        int    divStartIndex = 0;
                        int    divEndIndex   = 0;
                        string href          = "";

                        for (int j = 0; j < divCount; j++)
                        {
                            divStartIndex = pageSource.IndexOf(delimeter, divEndIndex);
                            divEndIndex   = pageSource.IndexOf("</div>", divStartIndex);

                            div[j] = pageSource.Substring(divStartIndex);
                            div[j] = div[j].Remove(divEndIndex - divStartIndex);

                            if (div[j].Replace("-", "").Contains(isbn) == true)
                            {
                                href = div[j].Substring(div[j].IndexOf(delimeter) + delimeter.Length);
                                href = href.Substring(href.IndexOf("\"") + 1);
                                href = href.Remove(href.IndexOf("\""));
                                href = "https://biznes.abe.pl" + href;
                                break;
                            }
                            else
                            {
                                // Если ни одна строка не содержит искомого ISBN тогда берем первую строку и забираем из нее ссылку
                                href = div[0].Substring(div[0].IndexOf(delimeter) + delimeter.Length);
                                href = href.Substring(href.IndexOf("\"") + 1);
                                href = href.Remove(href.IndexOf("\""));
                                href = "https://biznes.abe.pl" + href;
                            }
                        }
                        //==================================================================================================

                        request = (HttpWebRequest)WebRequest.Create(href);
                        request.CookieContainer = cookieContainer;

                        try
                        {
                            response   = (HttpWebResponse)request.GetResponse();
                            sr         = new StreamReader(response.GetResponseStream());
                            pageSource = sr.ReadToEnd();
                        }
                        catch
                        {
                            pageSource = string.Empty;
                        }
                        //==================================================================================================

                        // Блок обработки карточки товара. Пытаемся получить всю доступную информацию
                        if (pageSource != string.Empty)
                        {
                            pageSource = AlphabetCheck.Check(pageSource);

                            // Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
                            // Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
                            temp = "<dt>EAN</dt> <dd>";
                            string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));

                            if (isbn != checkISBN)
                            {
                                isbn2 = "ISBN не совпадает: " + checkISBN;
                            }

                            // Присваиваем наименование
                            temp  = "<div class=\"page-header\">";
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Substring(title.IndexOf("class=\"\">") + 9);
                            title = title.Remove(title.IndexOf("<"));

                            // Присваиваем автора
                            temp = "<dt>Author</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                author = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                author = author.Remove(author.IndexOf("<"));
                            }

                            // Присваиваем дату издания
                            temp = "<dt>Date</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            }

                            // Присваиваем Division
                            temp = "<dt>Division</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                imprint = imprint.Substring(imprint.IndexOf(">") + 1);
                                imprint = imprint.Remove(imprint.IndexOf("<"));
                            }

                            // Присваиваем издательство
                            temp = "<dt>Publisher</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                publisher = publisher.Substring(publisher.IndexOf(">") + 1);
                                publisher = publisher.Remove(publisher.IndexOf("<"));
                            }

                            // Присваиваем цену с валютой и без нее
                            temp = "<small class='text-green'>List price</small>";
                            if (pageSource.Contains(temp))
                            {
                                priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                priceWithCurrency = priceWithCurrency.Substring(priceWithCurrency.IndexOf("> ") + 2);
                                priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                                price             = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
                                price             = price.Replace(".", ",");
                            }

                            // Присваиваем цену со скидкой
                            temp = "<small class='text-green'>Your price</small>";
                            if (pageSource.Contains(temp))
                            {
                                discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                discount = discount.Substring(discount.IndexOf("> ") + 2);
                                discount = discount.Remove(discount.IndexOf("<"));
                                discount = discount.Remove(discount.IndexOf(" "));
                                discount = discount.Replace(".", ",");
                            }

                            // Присваиваем доступность
                            temp = "<span class=\"text-blue-first\">";
                            if (pageSource.Contains(temp))
                            {
                                availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                availability = availability.Substring(availability.IndexOf(">") + 1);
                                availability = availability.Remove(availability.IndexOf("<"));
                            }

                            // Присваиваем читательскую группу
                            temp = "<dt>Readership level</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                readership = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                readership = readership.Remove(readership.IndexOf("<"));
                            }

                            // Присваиваем издание
                            temp = "<dt>Edition</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                edition = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                edition = edition.Remove(edition.IndexOf("<"));
                            }

                            // Присваиваем обложку
                            temp = "<dt>Cover</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                bookCover = bookCover.Remove(bookCover.IndexOf("<"));
                            }

                            // Присваиваем страницы
                            temp = "<dt>Pages</dt> <dd>";
                            if (pageSource.Contains(temp))
                            {
                                pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                pages = pages.Remove(pages.IndexOf("<"));
                            }

                            // Присваиваем описание, убираем все лишнее из текста
                            temp = "<h3>Description</h3>";
                            if (pageSource.Contains(temp))
                            {
                                description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                description = description.Substring(description.IndexOf("<div class=\"col-md-12\">") + 23);
                                description = description.Remove(description.IndexOf("</div>"));

                                description = description.Replace("</p>", " "); // здесь меняем на пробел
                                description = description.Replace("</P>", " "); // здесь меняем на пробел

                                // Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
                                // Когда нашли индексы убираем содержимое между ними методом Remove

                                int  startIndex = 0;
                                int  lastIndex  = 0;
                                bool done       = false;

                                while (done != true)
                                {
                                    char[] tempDescription = description.ToCharArray();

                                    for (int j = 0; j < description.Length; j++)
                                    {
                                        if (tempDescription[j] == '<')
                                        {
                                            startIndex = j;
                                            break;
                                        }
                                    }
                                    for (int k = startIndex; k < description.Length; k++)
                                    {
                                        if (tempDescription[k] == '>')
                                        {
                                            lastIndex = k - startIndex + 1;
                                            break;
                                        }
                                    }
                                    description = description.Remove(startIndex, lastIndex);
                                    if (!description.Contains('<') && !description.Contains('>'))
                                    {
                                        description = AlphabetCheck.Check(description);
                                        done        = true;
                                    }
                                }
                                //==================================================================================================
                            }
                        }
                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Пример #7
0
        public Gardners(string[] isbns)
        {
            string loginPage     = "https://www.gardners.com/Account/LogOn";
            string isbnUrl       = "https://www.gardners.com/Product/";
            string accountNumber = "Номер аккаунта";
            string username      = "******";
            string password      = "******";

            string pageSource = string.Empty;
            string temp       = string.Empty;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            var cookieContainer = GetCookie(loginPage, accountNumber, username, password);

            try
            {
                for (int i = 0; i < isbns.Length; i++)
                {
                    // Пауза чтобы не нагружать сервер :)
                    Thread.Sleep(1000);

                    // Присваиваем порядковый номер
                    number = (i + 1).ToString();

                    // Присваиваем ISBN
                    isbn = isbns[i].Replace("\n", "");
                    isbn = isbn.Replace("\r", "");

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту Gardners. Обработано {i + 1} из {isbnsLength}";
                    PB.progressBar.Value++;
                    progressvalue++;
                    Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                    //==================================================================================================

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;

                        response   = (HttpWebResponse)request.GetResponse();
                        sr         = new StreamReader(response.GetResponseStream());
                        pageSource = sr.ReadToEnd();
                    }
                    //==================================================================================================

                    // Проверка, не слетел ли наш логин
                    if (pageSource.Contains("class=\"unauthenticated\">"))
                    {
                        MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
                        break;
                    }
                    //==================================================================================================

                    // Блок обработки страницы с ответом
                    if (pageSource != string.Empty && isbn != "")
                    {
                        //pageSource = AlphabetCheck.Check(pageSource);

                        // Проверяем, есть ли замена
                        temp = "<span class=\"replacedByLink\">";
                        if (pageSource.Contains(temp))
                        {
                            isbn2 = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            isbn2 = isbn2.Substring(isbn2.IndexOf(">") + 1);
                            isbn2 = isbn2.Remove(isbn2.IndexOf("<"));
                        }

                        // Присваиваем наименование
                        temp = "<div class=\"titleContributor\">";
                        if (pageSource.Contains(temp))
                        {
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Substring(title.IndexOf(">") + 1);
                            title = title.Remove(title.IndexOf("<"));
                            title = AlphabetCheck.Check(title);
                        }

                        // Присваиваем автора. Авторов может быть несколько ищем все строки
                        temp = "<span class=\"contributorRole\">";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf("<h2>") + 4);
                            temp = temp.Remove(temp.IndexOf("</h2>"));

                            string[] rows = temp.Split('\n');

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("<a href"))
                                {
                                    temp    = rows[j].Substring(rows[j].IndexOf("\">") + 2);
                                    temp    = temp.Remove(temp.IndexOf("<"));
                                    author += temp + ", ";
                                }
                            }
                            author = author.Remove(author.LastIndexOf(","));
                            author = AlphabetCheck.Check(author);
                        }

                        // Присваиваем дату издания
                        temp = "<span>Published:</span>";
                        if (pageSource.Contains(temp))
                        {
                            pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubDate = pubDate.Replace("<span>", "");
                            pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            pubDate = AlphabetCheck.Check(pubDate);
                        }

                        // Присваиваем издательство
                        temp = "<span>Publisher:</span>";
                        if (pageSource.Contains(temp))
                        {
                            publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            publisher = publisher.Substring(publisher.IndexOf("\">") + 2);
                            publisher = publisher.Remove(publisher.IndexOf("<"));
                            publisher = AlphabetCheck.Check(publisher);
                        }

                        // Присваиваем импринт
                        temp = "<span>Imprint:</span>";
                        if (pageSource.Contains(temp))
                        {
                            imprint = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imprint = imprint.Substring(imprint.IndexOf("\">") + 2);
                            imprint = imprint.Remove(imprint.IndexOf("<"));
                            imprint = AlphabetCheck.Check(imprint);
                        }

                        // Присваиваем цену с валютой и без нее
                        temp = "<span class=\"retailPrice\">";
                        if (pageSource.Contains(temp))
                        {
                            priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                            priceWithCurrency = priceWithCurrency.Replace("&#163;", "") + " GBP";
                            priceWithCurrency = priceWithCurrency.Replace(".", ",");
                            price             = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
                        }

                        // Присваиваем скидку
                        temp = "<p class=\"hideCustomer\"><span>";
                        if (pageSource.Contains(temp))
                        {
                            discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            discount = discount.Remove(discount.IndexOf(" "));
                        }

                        // Присваиваем доступность
                        temp = "<div class=\"availability\"";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</div>"));

                            string[] rows = temp.Split('\n');

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("class=\"icon-text"))
                                {
                                    temp          = rows[j].Substring(rows[j].IndexOf("icon-text"));
                                    temp          = temp.Substring(temp.IndexOf(">") + 1);
                                    temp          = temp.Remove(temp.IndexOf("<"));
                                    availability += temp + ", ";
                                }
                            }
                            availability = availability.Remove(availability.LastIndexOf(","));
                        }

                        // Присваиваем читательскую группу (Readership)
                        temp = "<span>Readership:</span>";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</ul>"));

                            string[] rows = temp.Split('\n');

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("<li>"))
                                {
                                    temp        = rows[j].Substring(rows[j].IndexOf(">") + 1);
                                    temp        = temp.Remove(temp.IndexOf("<"));
                                    readership += temp + ", ";
                                }
                            }
                            readership = readership.Remove(readership.LastIndexOf(","));
                            readership = AlphabetCheck.Check(readership);
                        }

                        // Присваиваем издание
                        temp = "<span class=\"edition\">";
                        if (pageSource.Contains(temp))
                        {
                            edition = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            edition = edition.Remove(edition.IndexOf("<"));
                        }

                        // Присваиваем вес
                        temp = "<span>Weight:</span>";
                        if (pageSource.Contains(temp))
                        {
                            weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            weight = weight.Replace("<span>", "");
                            weight = weight.Remove(weight.IndexOf("g"));
                            weight = ((float.Parse(weight)) / 1000).ToString();
                        }

                        // Присваиваем размеры
                        temp = "<span>Dimensions:</span>";
                        if (pageSource.Contains(temp))
                        {
                            dimensions = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            dimensions = dimensions.Replace("<span>", "");
                            dimensions = dimensions.Remove(dimensions.IndexOf(" <"));

                            string[] dim = dimensions.Split('x');
                            try
                            {
                                length = dim[0];
                                width  = dim[1];
                                height = dim[2];
                            }
                            catch { }
                        }

                        // Присваиваем страну происхождения
                        temp = "<span>Pub. Country:</span>";
                        if (pageSource.Contains(temp))
                        {
                            pubCountry = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubCountry = pubCountry.Replace("<span>", "");
                            pubCountry = pubCountry.Remove(pubCountry.IndexOf("<"));
                        }

                        // Присваиваем классификацию
                        temp = "<span>Classifications:</span>";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</ul>"));

                            string[] rows = temp.Split('\n');

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("<a href"))
                                {
                                    temp            = rows[j].Substring(rows[j].IndexOf("\">") + 2);
                                    temp            = temp.Remove(temp.IndexOf("<"));
                                    classification += temp + ", ";
                                }
                            }
                            classification = classification.Remove(classification.LastIndexOf(","));
                            classification = AlphabetCheck.Check(classification);
                        }

                        // Присваиваем обложку
                        temp = "<li class=\"format_title\">";
                        if (pageSource.Contains(temp))
                        {
                            bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            bookCover = bookCover.Remove(bookCover.IndexOf("<"));
                        }

                        // Присваиваем страницы
                        temp = "<li class=\"pagination\">";
                        if (pageSource.Contains(temp))
                        {
                            pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pages = pages.Remove(pages.IndexOf("<"));
                        }

                        // Присваиваем серию
                        temp = "<span>Series:</span>";
                        if (pageSource.Contains(temp))
                        {
                            series = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            series = series.Replace("<span>", "");
                            series = series.Substring(series.IndexOf(">") + 1);
                            series = series.Remove(series.IndexOf("<"));
                        }

                        // Присваиваем описание
                        temp = "<div class=\"productDescription\">";
                        if (pageSource.Contains(temp))
                        {
                            description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            description = description.Remove(description.IndexOf("</div>"));
                            description = description.Replace("<br>", " ");

                            // Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
                            // Когда нашли индексы убираем содержимое между ними методом Remove

                            int  startIndex = 0;
                            int  lastIndex  = 0;
                            bool done       = false;

                            while (done != true)
                            {
                                char[] tempDescription = description.ToCharArray();

                                for (int j = 0; j < description.Length; j++)
                                {
                                    if (tempDescription[j] == '<')
                                    {
                                        startIndex = j;
                                        break;
                                    }
                                }
                                for (int k = startIndex; k < description.Length; k++)
                                {
                                    if (tempDescription[k] == '>')
                                    {
                                        lastIndex = k - startIndex + 1;
                                        break;
                                    }
                                }
                                description = description.Remove(startIndex, lastIndex);
                                if (!description.Contains('<') && !description.Contains('>'))
                                {
                                    description = AlphabetCheck.Check(description);
                                    done        = true;
                                }
                            }
                            //==================================================================================================
                        }

                        // Присваиваем содержание
                        temp = "<span>Contents:</span>";
                        if (pageSource.Contains(temp))
                        {
                            contents = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            contents = contents.Replace("<span>", "");
                            contents = contents.Remove(contents.IndexOf("</span>"));
                            contents = AlphabetCheck.Check(contents);
                        }

                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Пример #8
0
        public Ingram(string[] isbns)
        {
            string loginPage = "https://ipage.ingramcontent.com/ipage/li001.jsp";
            string username  = "******";
            string password  = "******";

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            WebDriverWait wait5  = new WebDriverWait(cd, TimeSpan.FromSeconds(5));
            WebDriverWait wait10 = new WebDriverWait(cd, TimeSpan.FromSeconds(10));
            WebDriverWait wait16 = new WebDriverWait(cd, TimeSpan.FromSeconds(16));

            try
            {
                cd.Url = loginPage;
                IWebElement element;

                // КОД для логина и пароля
                element = cd.FindElement(By.Id("userIDText"));
                element.SendKeys(username);
                element = cd.FindElement(By.Id("passwordText"));
                element.SendKeys(password);

                element = cd.FindElement(By.XPath("//button[@class = 'btn btn-primary btn-block']"));
                element.Click();

                try
                {
                    for (int i = 0; i < isbns.Length; i++)
                    {
                        // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                        PB.Title = $"Поиск по сайту Ingram. Обработано {i + 1} из {isbnsLength}";
                        PB.progressBar.Value++;
                        progressvalue++;
                        Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                              new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                        //==================================================================================================

                        number = (i + 1).ToString();
                        isbn   = isbns[i].Replace("\n", "");
                        isbn   = isbn.Replace("\r", "");

                        if (isbns[i] != string.Empty)
                        {
                            element = cd.FindElement(By.XPath("//*[@id = 'searchText']"));
                            element.Clear();
                            element.SendKeys(isbns[i]);
                            element.SendKeys(Keys.Enter);

                            try
                            {
                                // КОД для определения нашлась ли искомая позиция
                                element        = cd.FindElement(By.XPath("//div[@class = 'toggleBox, searchCorrect  top-row breadcrum-section']"));
                                AdvancedSearch = true;
                            }
                            catch { }

                            if (AdvancedSearch != true)
                            {
                                try // Поиск наименования
                                {
                                    element = cd.FindElement(By.XPath("//span[@class = 'productDetailTitle']"));
                                    title   = element.Text;
                                }
                                catch { }

                                try // Поиск автора
                                {
                                    element = cd.FindElement(By.XPath("//a[@class = 'doContributorSearch']/span"));
                                    author  = element.Text;
                                }
                                catch { }

                                try // Поиск даты издания
                                {
                                    element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'Pub Date:')]]"));
                                    pubDate = element.Text;
                                    pubDate = pubDate.Replace("Pub Date: ", "");
                                }
                                catch { }

                                try // Поиск издательства
                                {
                                    element   = cd.FindElement(By.XPath("//a[@class = 'doSid']"));
                                    publisher = element.Text;
                                }
                                catch { }

                                try // Поиск цены
                                {
                                    element           = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'US SRP:')]]"));
                                    priceWithCurrency = element.Text;
                                    priceWithCurrency = priceWithCurrency.Replace("US SRP: $", "");
                                    priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" ")) + " USD"; // удалить весть текст после " "
                                    price             = priceWithCurrency.Replace(" USD", "");
                                    price             = price.Replace(".", ",");
                                }
                                catch { }

                                try // Поиск скидки
                                {
                                    element  = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'US SRP:')]]"));
                                    discount = element.Text;
                                    discount = discount.Replace("REG", "42%");
                                    discount = discount.Remove(discount.IndexOf(")"));             // удалить весть текст после (и включительно) "%", если % нужно оставить, то проставить +1
                                    discount = discount.Substring(discount.IndexOf("Discount: ")); // удалить все до символа
                                    discount = discount.Replace("Discount: ", "");
                                    discount = discount.Replace("%", "");
                                }
                                catch { }

                                try // Поиск доступности
                                {
                                    element      = cd.FindElement(By.XPath("//span[@class = 'productDetailTitle']/following-sibling::strong"));
                                    availability = element.Text;
                                    availability = availability.Replace("- ", "");
                                }
                                catch { }

                                try // Поиск доступности с количествами по разным складам
                                {
                                    bool result;
                                    int  temp1 = 0;
                                    int  temp2 = 0;
                                    int  temp3 = 0;
                                    int  temp4 = 0;
                                    int  temp5 = 0;
                                    int  temp6 = 0;
                                    int  temp;

                                    IWebElement availabilityTN = cd.FindElement(By.XPath("//table[@class = 'newStockCheckTable']//tr[3]//td[@class = 'scTabledata']"));
                                    availability = "In stock TN: " + availabilityTN.Text;
                                    availability = availability.Replace(",", "");

                                    try
                                    {
                                        IWebElement availabilityPAC = cd.FindElement(By.XPath("//table[@class = 'newStockCheckTable']//tr[2]//td[@class = 'scTabledata']"));
                                        result = Int32.TryParse(availabilityPAC.Text.Replace(",", ""), out temp1);
                                    }
                                    catch { }

                                    try
                                    {
                                        IWebElement availabilityCA = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[1]//td[@class = 'scTabledata']"));
                                        result = Int32.TryParse(availabilityCA.Text.Replace(",", ""), out temp2);
                                    }
                                    catch { }

                                    try
                                    {
                                        IWebElement availabilityIN = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[2]//td[@class = 'scTabledata']"));
                                        result = Int32.TryParse(availabilityIN.Text.Replace(",", ""), out temp3);
                                    }
                                    catch { }

                                    try
                                    {
                                        IWebElement availabilityOH = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[3]//td[@class = 'scTabledata']"));
                                        result = Int32.TryParse(availabilityOH.Text.Replace(",", ""), out temp4);
                                    }
                                    catch { }

                                    try
                                    {
                                        IWebElement availabilityOR = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[4]//td[@class = 'scTabledata']"));
                                        result = Int32.TryParse(availabilityOR.Text.Replace(",", ""), out temp5);
                                    }
                                    catch { }

                                    try
                                    {
                                        IWebElement availabilityPAA = cd.FindElement(By.XPath("//table[@class = 'newAltStockCheckTable']//tr[5]//td[@class = 'scTabledata']"));
                                        result = Int32.TryParse(availabilityPAA.Text.Replace(",", ""), out temp6);
                                    }
                                    catch { }

                                    temp          = temp1 + temp2 + temp3 + temp4 + temp5 + temp6;
                                    availability2 = "Another warehouses: " + temp.ToString();
                                }
                                catch { }

                                try // Поиск Readership
                                {
                                    element    = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Target Age Group:')]]"));
                                    readership = element.Text;
                                    readership = readership.Replace("Target Age Group: ", "");
                                }
                                catch { }

                                try // Поиск веса
                                {
                                    element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Physical Info:')]]"));
                                    weight  = element.Text;
                                    weight  = weight.Substring(weight.IndexOf("(") + 1); // удалить все до символа
                                    weight  = weight.Remove(weight.IndexOf(") "));       // удалить весть текст после (и включительно) ")", если ) нужно оставить, то проставить +1
                                }
                                catch { }

                                try // Поиск размеров
                                {
                                    element    = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Physical Info:')]]"));
                                    dimensions = element.Text;
                                    dimensions = dimensions.Replace("Physical Info: ", "");
                                    dimensions = dimensions.Remove(dimensions.IndexOf("(")); // удалить весть текст после (и включительно) "(", если ( нужно оставить, то проставить +1
                                    dimensions = dimensions.Replace(" H", "");
                                    dimensions = dimensions.Replace(" L", "");
                                    dimensions = dimensions.Replace(" W", "");

                                    string[] temp = dimensions.Split('x');
                                    temp[0] = temp[0].Replace(" cms", ""); //Width (mm)
                                    temp[1] = temp[1].Replace(" cms", ""); //Height (mm)
                                    temp[2] = temp[2].Replace(" cms", ""); //Lenght (mm)

                                    temp[0] = temp[0].Replace(".", ",");
                                    temp[1] = temp[1].Replace(".", ",");
                                    temp[2] = temp[2].Replace(".", ",");

                                    double temp1 = Convert.ToDouble(temp[2]);
                                    temp1  = temp1 * 10;
                                    height = temp1.ToString();

                                    double temp2 = Convert.ToDouble(temp[1]);
                                    temp2 = temp2 * 10;
                                    width = temp2.ToString();

                                    double temp3 = Convert.ToDouble(temp[0]);
                                    temp3  = temp3 * 10;
                                    length = temp3.ToString();
                                }
                                catch { }

                                try // Поиск обложки
                                {
                                    element   = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and ./strong[contains(text(), 'Binding:')]]"));
                                    bookCover = element.Text;
                                    bookCover = bookCover.Replace("Binding: ", "");
                                }
                                catch { }

                                try // Поиск количества страниц
                                {
                                    element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Physical Info:')]]"));
                                    pages   = element.Text;
                                    pages   = pages.Substring(pages.IndexOf(")") + 1);
                                }
                                catch { }

                                try // Поиск серии
                                {
                                    element = cd.FindElement(By.XPath("//td[@class = 'productDetailSmallElements' and ./strong[contains(text(), 'Series:')]]/a"));
                                    series  = element.Text;
                                }
                                catch { }

                                try // Поиск описания
                                {
                                    element     = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'Annotation:')]]/div/div"));
                                    description = element.Text;
                                    description = description.Replace("\n", "");
                                    description = description.Replace("\r", "");
                                    description = description.Replace("\r\n", "");
                                    try
                                    {
                                        element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'Annotation:')]]/div/a"));
                                        element.Click();

                                        element     = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'Annotation:')]]/div[2]/div"));
                                        description = element.Text;
                                        description = description.Replace("\n", "");
                                        description = description.Replace("\r", "");
                                        description = description.Replace("\r\n", "");
                                    }
                                    catch { }
                                }
                                catch { }

                                try // Поиск второго ISBN
                                {
                                    element = cd.FindElement(By.XPath("//div[@class = 'newerVersionAvailable']/a"));
                                    element.Click();

                                    try
                                    {
                                        element = cd.FindElement(By.XPath("//div[@class = 'productDetailElements' and .//strong[contains(text(), 'EAN:')]]"));
                                        isbn2   = element.Text;
                                        isbn2   = isbn2.Substring(isbn2.IndexOf("EAN:"));
                                        isbn2   = isbn2.Replace("EAN:", "");
                                    }
                                    catch { }
                                }
                                catch { }
                            }
                            AdvancedSearch = false;
                            AddBookToList();
                            ClearBookList();
                        }
                    }
                }
                catch (Exception ex)
                {
                    cd.Quit();
                    PB.Close();
                    Errors.CustomError(ex);
                }
                cd.Quit();
                WorkWithFile.SaveFile(book);
                PB.Close();
            }
            catch (Exception ex)
            {
                cd.Quit();
                PB.Close();
                Errors.LoginPageError(ex);
            }
        }
Пример #9
0
        public Libri(string[] isbns)
        {
            string loginPage     = "https://mein.libri.de/en/Login.html";
            string isbnUrl       = "https://mein.libri.de/en/produkt/";
            string accountNumber = "Номер аккаунта";
            string username      = "******";
            string password      = "******";

            string pageSource = string.Empty;
            string temp       = string.Empty;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            cookieContainer = GetCookie(loginPage, accountNumber, username, password);

            try
            {
                for (int i = 0; i < isbns.Length; i++)
                {
                    pageSource = string.Empty;
                    // Пауза чтобы не нагружать сервер :)
                    Thread.Sleep(1000);

                    // Присваиваем порядковый номер
                    number = (i + 1).ToString();

                    // Присваиваем ISBN
                    isbn = isbns[i].Replace("\n", "");
                    isbn = isbn.Replace("\r", "");

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту Libri. Обработано {i + 1} из {isbnsLength}";
                    PB.progressBar.Value++;
                    progressvalue++;
                    Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                    //==================================================================================================

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;

                        response   = (HttpWebResponse)request.GetResponse();
                        sr         = new StreamReader(response.GetResponseStream());
                        pageSource = sr.ReadToEnd();
                    }
                    //==================================================================================================

                    // Проверка, не слетел ли наш логин
                    if (pageSource.Contains("Please enter your login information."))
                    {
                        MessageBox.Show("Не удалось авторизоваться. Поиск остановлен.");
                        break;
                    }
                    //==================================================================================================

                    // Блок обработки страницы с ответом
                    if (pageSource != string.Empty)
                    {
                        pageSource = AlphabetCheck.Check(pageSource);

                        // Блок проверки соответствия ISBN. Сравниваем тот ISBN который был в списке с тем что нашли.
                        // Если они не равны, тогда в столбце ISBN2 указываем что ISBN не совпадает.
                        temp = "Article no./EAN";
                        if (pageSource.Contains(temp))
                        {
                            string checkISBN = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            checkISBN = checkISBN.Substring(checkISBN.IndexOf("<td>") + 4);
                            checkISBN = checkISBN.Remove(checkISBN.IndexOf("<"));
                            checkISBN = AlphabetCheck.Check(checkISBN);

                            if (isbn != checkISBN)
                            {
                                isbn2 = "ISBN не совпадает: " + checkISBN;
                            }
                        }

                        // Присваиваем наименование
                        temp = "<div class=\"col-md-6\"><h1>";
                        if (pageSource.Contains(temp))
                        {
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Remove(title.IndexOf("<"));
                            title = AlphabetCheck.Check(title);
                        }

                        // Присваиваем автора
                        temp = "<td class=\"detail-label\"> Author </td>";
                        if (pageSource.Contains(temp))
                        {
                            author = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            author = author.Replace("<td>", "");
                            author = author.Remove(author.IndexOf("</td>"));
                            author = author.Replace("<br>", ";");
                            author = AlphabetCheck.Check(author);
                        }

                        // Присваиваем дату издания
                        temp = "<td class=\"detail-label\"> Release date </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            pubDate = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            pubDate = AlphabetCheck.Check(pubDate);
                        }

                        // Присваиваем издательство
                        temp = "<td class=\"detail-label\"> Publisher </td> <td class=\"info-column\">";
                        if (pageSource.Contains(temp))
                        {
                            publisher = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            publisher = publisher.Remove(publisher.IndexOf("<"));
                            publisher = AlphabetCheck.Check(publisher);
                        }

                        // Присваиваем цену с валютой и без нее
                        temp = "<span class=\"price\">";
                        if (pageSource.Contains(temp))
                        {
                            priceWithCurrency = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            priceWithCurrency = priceWithCurrency.Remove(priceWithCurrency.IndexOf("<"));
                            priceWithCurrency = priceWithCurrency.Replace(".", ",");
                            price             = priceWithCurrency.Remove(priceWithCurrency.IndexOf(" "));
                        }

                        // Присваиваем скидку
                        temp = "<td class=\"detail-label\"> Discount group </td>";
                        if (pageSource.Contains(temp))
                        {
                            discount = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            discount = discount.Substring(discount.IndexOf("content=\"") + 9);
                            discount = discount.Remove(discount.IndexOf("\""));
                            discount = discount.Replace("<br>", "; ");
                            try
                            {
                                discount = discount.Remove(discount.LastIndexOf(";"));
                            }
                            catch { }
                        }

                        // Присваиваем доступность
                        temp = "<td class=\"detail-label\"> Availability Status Code </td>";
                        if (pageSource.Contains(temp))
                        {
                            availability = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            availability = availability.Substring(availability.IndexOf("content=\"") + 9);
                            availability = availability.Remove(availability.IndexOf("\""));
                        }

                        // Присваиваем читательскую группу (Readership)
                        temp = "<td class=\"detail-label\"> Age group </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            readership = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            readership = readership.Remove(readership.IndexOf("<"));
                        }

                        // Присваиваем вес
                        temp = "<td class=\"detail-label\"> Weight </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            weight = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            weight = weight.Remove(weight.IndexOf("g"));
                            weight = ((float.Parse(weight)) / 1000).ToString();
                        }

                        // Присваиваем классификацию
                        temp = "<td class=\"detail-label\"> Product group </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            classification = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            classification = classification.Remove(classification.IndexOf("<"));
                        }

                        // Присваиваем обложку
                        temp = "<td class=\"detail-label\"> Book cover </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            bookCover = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            bookCover = bookCover.Remove(bookCover.IndexOf("<"));
                        }

                        // Присваиваем страницы
                        temp = "<td class=\"detail-label\"> Pages </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            pages = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            pages = pages.Remove(pages.IndexOf("<"));
                        }

                        // Присваиваем серию
                        temp = "<td class=\"detail-label\"> Series </td> <td>";
                        if (pageSource.Contains(temp))
                        {
                            series = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            series = series.Remove(series.IndexOf("<"));
                        }

                        // Присваиваем описание
                        temp = "<div class=\"detail-content detail-description\">";
                        if (pageSource.Contains(temp))
                        {
                            description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            description = description.Remove(description.IndexOf("<"));
                        }

                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Пример #10
0
        public Brill(string[] isbns)
        {
            string isbnUrl    = "https://brill.com/search?q1=";
            string pageSource = string.Empty;
            string temp       = string.Empty;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            try
            {
                for (int i = 0; i < isbns.Length; i++)
                {
                    // Пауза чтобы не нагружать сервер :)
                    Thread.Sleep(1000);

                    // Присваиваем порядковый номер
                    number = (i + 1).ToString();

                    // Присваиваем ISBN
                    isbn = isbns[i].Replace("\n", "");
                    isbn = isbn.Replace("\r", "");

                    // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                    PB.Title = $"Поиск по сайту Brill. Обработано {i + 1} из {isbnsLength}";
                    PB.progressBar.Value++;
                    progressvalue++;
                    Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                          new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                    //==================================================================================================

                    // Отправляем первый запрос по ISBN. Ответом нам будет страница с карточкой товара
                    if (isbn != "")
                    {
                        request = (HttpWebRequest)WebRequest.Create(isbnUrl + isbn);
                        request.CookieContainer = cookieContainer;

                        response   = (HttpWebResponse)request.GetResponse();
                        sr         = new StreamReader(response.GetResponseStream());
                        pageSource = sr.ReadToEnd();
                    }
                    //==================================================================================================

                    // Блок обработки страницы с ответом
                    if (pageSource != string.Empty && isbn != "")
                    {
                        pageSource = AlphabetCheck.Check(pageSource);

                        // Присваиваем наименование
                        temp = "<div class=\"typography-body text-headline color-primary\">";
                        if (pageSource.Contains(temp))
                        {
                            title = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            title = title.Substring(title.IndexOf(">") + 1);
                            title = title.Remove(title.IndexOf("<"));
                            //title = AlphabetCheck.Check(title);
                        }

                        // Присваиваем автора. Авторов может быть несколько ищем все строки
                        temp = "<div class=\"contributor-line text-subheading\">";
                        if (pageSource.Contains(temp))
                        {
                            temp = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            temp = temp.Remove(temp.IndexOf("</div>"));

                            string[] rows = Regex.Split(temp, "</span>");

                            for (int j = 0; j < rows.Length; j++)
                            {
                                if (rows[j].Contains("</a>"))
                                {
                                    temp    = rows[j].Substring(rows[j].IndexOf("\">") + 2);
                                    temp    = temp.Remove(temp.IndexOf("<"));
                                    author += temp + ", ";
                                }
                            }
                            try
                            {
                                author = author.Remove(author.LastIndexOf(","));
                                //author = AlphabetCheck.Check(author);
                            }
                            catch
                            {
                                author = string.Empty;
                            }
                        }

                        // Присваиваем описание
                        temp = "<div id=\"ABSTRACT_OR_EXCERPT";
                        if (pageSource.Contains(temp))
                        {
                            try
                            {
                                description = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                                description = description.Substring(description.IndexOf(">") + 1);
                                description = description.Remove(description.IndexOf("</div>"));

                                // Иногда в описании присутствуют ссылки (текст содержит <a href = ...>), ищем индексы символов "<" и ">"
                                // Когда нашли индексы убираем содержимое между ними методом Remove

                                int  startIndex = 0;
                                int  lastIndex  = 0;
                                bool done       = false;

                                while (done != true)
                                {
                                    char[] tempDescription = description.ToCharArray();

                                    for (int j = 0; j < description.Length; j++)
                                    {
                                        if (tempDescription[j] == '<')
                                        {
                                            startIndex = j;
                                            break;
                                        }
                                    }
                                    for (int k = startIndex; k < description.Length; k++)
                                    {
                                        if (tempDescription[k] == '>')
                                        {
                                            lastIndex = k - startIndex + 1;
                                            break;
                                        }
                                    }
                                    description = description.Remove(startIndex, lastIndex);
                                    if (!description.Contains('<') && !description.Contains('>'))
                                    {
                                        //description = AlphabetCheck.Check(description);
                                        done = true;
                                    }
                                }
                            }
                            catch
                            {
                                description = string.Empty;
                            }
                        }

                        // Присваиваем ссылку на картинку
                        temp = "<div class=\"cover cover-image configurable-index-card-cover-image\">";
                        if (pageSource.Contains(temp))
                        {
                            imageUrl = pageSource.Substring(pageSource.IndexOf(temp) + temp.Length);
                            imageUrl = imageUrl.Substring(imageUrl.IndexOf(">") + 1);
                            imageUrl = imageUrl.Substring(imageUrl.IndexOf("src=\"") + 5);
                            imageUrl = "https://brill.com" + imageUrl.Remove(imageUrl.IndexOf(".") + 4);
                        }

                        temp = "<div class=\"content-box-body null\">";
                        if (pageSource.Contains(temp))
                        {
                            string[] body        = Regex.Split(pageSource, temp);
                            string[] meta        = null;
                            string   mainContent = null;
                            for (int j = 0; j < body.Length; j++)
                            {
                                if (body[j].Contains("<div class=\"text-metadata-format\">"))
                                {
                                    body[j] = body[j].Replace("-", "");
                                    meta    = Regex.Split(body[j], "<div class=\"textmetadataformat\">");
                                    break;
                                }
                            }

                            for (int j = 0; j < meta.Length; j++)
                            {
                                if (meta[j].Contains(isbn))
                                {
                                    mainContent = meta[j];
                                }
                            }

                            try
                            {
                                bookCover = mainContent.Remove(mainContent.IndexOf("<"));
                            }
                            catch { }
                            try
                            {
                                temp         = "<dd class=\"availability inline cList__item cList__item  secondary textmetadatavalue\">";
                                availability = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
                                availability = availability.Remove(availability.IndexOf("<"));
                            }
                            catch { }
                            try
                            {
                                temp    = "<dd class=\"pubdate inline cList__item cList__item  secondary textmetadatavalue\">";
                                pubDate = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
                                pubDate = pubDate.Remove(pubDate.IndexOf("<"));
                            }
                            catch { }
                            try
                            {
                                temp  = "</abbr>";
                                price = mainContent.Substring(mainContent.IndexOf(temp) + temp.Length);
                                price = price.Remove(price.IndexOf("<"));
                                price = price.Replace("€", "");
                                price = price.Replace(".", ",");
                            }
                            catch { }
                        }

                        AddBookToList();
                        ClearBookList();
                    }
                    else
                    {
                        AddBookToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.CustomError(ex);
            }
            WorkWithFile.SaveFile(book);

            PB.Close();
        }
Пример #11
0
        public AmericanPubEasy(string[] isbns)
        {
            string loginPage = "https://beta.pubeasy.com/static/pubeasy/index.html";
            string login     = "******";
            string username  = "******";
            string password  = "******";
            bool   notFound  = false;

            // Настраиваем Progress Bar
            PB.Show();
            int isbnsLength = isbns.Length;

            PB.progressBar.Minimum = 0;
            PB.progressBar.Maximum = isbnsLength;
            PB.progressBar.Value   = 0;
            double progressvalue = 1;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(PB.progressBar.SetValue);

            Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
            //==================================================================================================

            WebDriverWait wait5  = new WebDriverWait(cd, TimeSpan.FromSeconds(5));
            WebDriverWait wait10 = new WebDriverWait(cd, TimeSpan.FromSeconds(10));
            WebDriverWait wait16 = new WebDriverWait(cd, TimeSpan.FromSeconds(16));

            try
            {
                cd.Url = loginPage;
                IWebElement element;

                element = cd.FindElement(By.XPath("//li/a[contains(@href, 'login')]"));
                element.Click();

                // КОД для логина и пароля
                element = cd.FindElement(By.Id("login-id"));
                element.SendKeys(login);
                element = cd.FindElement(By.Id("user-id"));
                element.SendKeys(username);
                element = cd.FindElement(By.Id("login-password"));
                element.SendKeys(password);

                element = cd.FindElement(By.XPath("//input[contains(@type, 'submit')]"));
                element.Click();

                // Переключаемся на американский PubEasy
                element = cd.FindElement(By.XPath("//a[@class = 'nav-link' and contains(@href, '#us-tab')]"));
                element.Click();

                //Жмем кнопку SEARCH NOW ============================================================
                wait5.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@id = 'us-tab']//a")));
                element = cd.FindElement(By.XPath("//div[@id = 'us-tab' and .//a[text() = 'SEARCH NOW >']]//a"));
                element.Click();
                //===================================================================================

                try
                {
                    for (int i = 0; i < isbns.Length; i++)
                    {
                        // Присваиваем порядковый номер
                        number = (i + 1).ToString();

                        // Присваиваем ISBN
                        isbn = isbns[i].Replace("\n", "");
                        isbn = isbn.Replace("\r", "");

                        // Передаем данные в Progress Bar для увеличения шкалы и обновления UI
                        PB.Title = $"Поиск по сайту American PubEasy. Обработано {i + 1} из {isbnsLength}";
                        PB.progressBar.Value++;
                        progressvalue++;
                        Application.Current.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background,
                                                              new object[] { System.Windows.Controls.ProgressBar.ValueProperty, progressvalue });
                        //==================================================================================================

                        if (isbn != string.Empty)
                        {
                            // Переключаем драйвер на первую вкладку браузера
                            // cd.SwitchTo().Window(cd.WindowHandles.First());

                            element = cd.FindElement(By.XPath("//*[@id = 'search']/input"));
                            element.Clear();
                            element.SendKeys(isbn);
                            element.SendKeys(Keys.Enter);

                            try
                            {
                                // КОД для определения нашлась ли искомая позиция
                                element  = cd.FindElement(By.XPath("//strong[contains(text(), 'No records found')]"));
                                notFound = true;
                                cd.Navigate().Back();
                            }
                            catch { }

                            if (notFound != true)
                            {
                                try // Поиск наименования
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']//a[2]/font"));
                                    title   = element.Text;
                                    title   = title.Replace("\n", " ");
                                    title   = title.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск автора
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[2]"));
                                    author  = element.Text;
                                }
                                catch { }

                                try // Поиск даты издания
                                {
                                    element = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[6]"));
                                    pubDate = element.Text;
                                    pubDate = pubDate.Replace("\n", " ");
                                    pubDate = pubDate.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск издательства
                                {
                                    element   = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[4]"));
                                    publisher = element.Text;
                                }
                                catch { }

                                try // Поиск поставщика
                                {
                                    element  = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[5]"));
                                    supplier = element.Text;
                                }
                                catch { }

                                try // Поиск цены
                                {
                                    element           = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[7]"));
                                    priceWithCurrency = element.Text;

                                    // проверка на валюту, если в строке валюта CAD в этом случае пытаемся взять значение цены из второй строки, т.к. нам нужны только цены в USD
                                    if (priceWithCurrency.Contains("CAD"))
                                    {
                                        try
                                        {
                                            priceWithCurrency = cd.FindElement(By.XPath("//tr[@class = 'even']/td[7]")).Text;
                                        }
                                        catch
                                        {
                                            priceWithCurrency = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[7]")).Text;
                                        }
                                    }

                                    priceWithCurrency = priceWithCurrency.Replace("\r\n", " ");
                                    priceWithCurrency = priceWithCurrency.Replace(" (Retail)", "");
                                    priceWithCurrency = priceWithCurrency.Replace(" (List)", "");
                                    price             = priceWithCurrency.Replace(" USD", "");
                                    price             = price.Replace(".", ",");
                                }
                                catch { }

                                try // Поиск доступности
                                {
                                    element      = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[8]"));
                                    availability = element.Text;
                                    availability = availability.Replace("\n", " ");
                                    availability = availability.Replace("\r", " ");
                                }
                                catch { }

                                try // Поиск обложки
                                {
                                    element   = cd.FindElement(By.XPath("//tr[@class = 'odd']/td[3]"));
                                    bookCover = element.Text;
                                }
                                catch { }

                                if (supplier.StartsWith("bertram", StringComparison.OrdinalIgnoreCase) |
                                    supplier.StartsWith("gardners", StringComparison.OrdinalIgnoreCase))
                                {
                                    ClearBookList();
                                }
                            }
                            AddBookToList();
                            ClearBookList();
                            notFound = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    cd.Quit();
                    PB.Close();
                    Errors.CustomError(ex);
                }
                cd.Quit();
                PB.Close();
                WorkWithFile.SaveFile(book);
            }
            catch (Exception ex)
            {
                cd.Quit();
                PB.Close();
                Errors.LoginPageError(ex);
            }
        }