예제 #1
0
        static void Main(string[] args)
        {
            string addressFrom = @"C:\Users\Andrew\Desktop\Таня\TestC-\DZ1\Текстовые файлы\TextFile1.txt";
            string addressTo   = @"C:\Users\Andrew\Desktop\Таня\TestC-\DZ1\Текстовые файлы\TextFile2.txt";

            WorkWithFile.copy(Path.GetFullPath(addressFrom), Path.GetFullPath(addressTo));
        }
예제 #2
0
        private void SaveAsExcel(List <PriceModel> priceList)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            ExcelPackage   excelPackage = new ExcelPackage();
            ExcelWorksheet worksheet    = excelPackage.Workbook.Worksheets.Add(DateTime.Now.ToString("dd.MM.yyyy"));

            // Добавляем шапку в первую строку
            worksheet.Cells["A1"].Value = "#";
            worksheet.Cells["B1"].Value = "ISBN";
            worksheet.Cells["C1"].Value = "Наименование товара";
            worksheet.Cells["D1"].Value = "Цена с НДС";
            worksheet.Cells["E1"].Value = "НДС";
            worksheet.Cells["F1"].Value = "Группа товара";
            worksheet.Cells["G1"].Value = "Кол-во на складе";
            worksheet.Cells["H1"].Value = "Кол-во в магазине";
            worksheet.Cells["I1"].Value = "Краткое наименование";

            // Добавляем данные из priceList начиная со второй строки
            worksheet.Cells["A2"].LoadFromCollection(priceList);

            // Устанавливаем ширину столбцов, кроме последнего ("Краткое наименование")
            worksheet.Column(1).AutoFit();      // #
            worksheet.Column(2).Width = 16;     // ISBN
            worksheet.Column(3).Width = 110;    // Наименование товара
            worksheet.Column(4).Width = 15;     // Цена с НДС
            worksheet.Column(5).Width = 7;      // НДС
            worksheet.Column(6).Width = 22;     // Группа товара
            worksheet.Column(7).Width = 20;     // Кол-во на складе
            worksheet.Column(8).Width = 20;     // Кол-во в магазине
            worksheet.Column(9).Width = 25;     // краткое наименование

            // Устанавливаем границы, автофильтр, жирный шрифт для шапки, закрепляем первую строку,
            // а также меняем цифровой формат для столбца с ценами
            worksheet.Column(4).Style.Numberformat.Format = "0.00";
            worksheet.View.FreezePanes(2, 1);
            worksheet.Cells["A1:I1"].Style.Font.Bold = true;
            worksheet.Cells["A1:I1"].AutoFilter      = true;
            worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Top.Style    = ExcelBorderStyle.Thin;
            worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Right.Style  = ExcelBorderStyle.Thin;
            worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
            worksheet.Cells["A1:I" + (priceList.Count + 1)].Style.Border.Left.Style   = ExcelBorderStyle.Thin;

            // Сохраняем файл
            SaveFileDialog sfd      = new SaveFileDialog();
            string         fileName = "Price roznitca " + DateTime.Now.ToString("dd.MM.yyyy"); // имя файла по-умолчанию

            sfd.Title      = "Сохранить прайс-лист ...";
            sfd.DefaultExt = ".xlsx";
            sfd.FileName   = fileName;
            sfd.Filter     = "Excel (*.xlsx) | *.xlsx";

            if (sfd.ShowDialog() == true)
            {
                FileInfo fi = new FileInfo(sfd.FileName);
                excelPackage.SaveAs(fi);
                WorkWithFile.AddPriceToZIP(sfd.FileName);
            }
        }
예제 #3
0
        public MainWindow()
        {
            InitializeComponent();

            // Для вкладки Прайс-лист подгружаем из файла группы для исключения (если нет папки или файла - создаем)
            groupsForExclude.Text = WorkWithFile.CheckForExceptionsFileExistance(
                exceptionsDirectory,
                exceptionsFilePath
                );

            // На вкладке Прайс-лист выключаем кнопку Сохранить (включается, если будут изменения в поле с группами для исключений)
            saveGroupsBtn.IsEnabled = false;

            // Проверяем, есть ли файл базы данных (если нет то создаем). База используется только для хранения сгенерированных кодов
            WorkWithFile.CreateDataBase(
                dbName,
                dbPath
                );
        }
예제 #4
0
        public void ReadFromFile()
        {
            mut.WaitOne();

            WorkWithFile workWithFile = new WorkWithFile();

            p = workWithFile.ReadFromFile(fileName);
            MessageBox.Show("Файл считан", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
            if (p.Length == 0)
            {
                return;
            }
            построитьПолиномToolStripMenuItem.Visible = true;

            waitRead.Set();
            mut.ReleaseMutex();
            Thread sortFile = new Thread(SortFile);

            sortFile.Start();
        }
예제 #5
0
        static void Main(string[] args)
        {
            WorkWithFile.CreateFile();
            string[] massOfpropertiesFromUser = Console.ReadLine().Split(',');

            foreach (var property in typeof(Person).GetProperties())
            {
                foreach (var userProperty in massOfpropertiesFromUser)
                {
                    using (StreamWriter file = new StreamWriter("properties.csv", true))
                    {
                        string str = property.Name == userProperty ? property.Name + "\n" + string.Join("\n", PersonList.GetListPerson()
                                                                                                        .Select(x => typeof(Person)
                                                                                                                .GetProperty(userProperty, BindingFlags.Instance | BindingFlags.Public)
                                                                                                                .GetValue(x, null))) : "";

                        file.WriteLine(str);
                    }
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Метод кластеризации Dbscan с использованием R*-дерева
        /// </summary>
        /// <param name="path">Путь до файла с точками</param>
        /// <param name="eps"></param>
        /// <param name="minPTS"></param>
        void UseOnlyDBScanwithRtree(string path, double eps, int minPTS)
        {
            bool         check  = true;
            List <Point> points = new List <Point>(0);

            try
            {
                points             = WorkWithFile.GetPointFromFile(path);
                progressBar1.Value = 30;
            }
            catch (ArgumentException ex)
            {
                check = false;
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                progressBar1.Value = 0;
            }

            if (check)
            {
                Stopwatch dbscantime = new Stopwatch();

                int count_of_db;
                //if (ForRstartree.MAX_M )
                dbscantime.Start();

                Dbscanwithrtree.Clustering(points, eps, minPTS, out count_of_db);

                dbscantime.Stop();
                progressBar1.Value = 70;
                MessageBox.Show("Количество точек: " + points.Count + "\n" + "Время выполнения DBScan с R*-деревом: " + dbscantime.Elapsed.Seconds + " сек." + "\n" + "Скорость выполнения: " + $"{ ((dbscantime.Elapsed.Seconds > 0) ? (points.Count / dbscantime.Elapsed.Seconds) : points.Count):F2} точки в сек.", "Время выполнения", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Graph.Graphic f2 = new Graph.Graphic(points, count_of_db, dbscantime, "Алгоритм кластеризации DBscan с использованием R*-дерева");
                progressBar1.Value = 100;
                f2.Show();
            }
            progressBar1.Value = 100;
        }
예제 #7
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);
            }
        }
예제 #8
0
        public DoPriceList(string exceptionsList, bool?fullPrice)
        {
            List <PriceModel> priceList = new List <PriceModel>();
            CultureInfo       culture   = CultureInfo.CreateSpecificCulture("en-US");

            exceptionsList = exceptionsList.Replace("\r", "");
            string[] exceptions = exceptionsList.Split('\n');
            string[] fileText   = WorkWithFile.OpenFile();
            string[,] price;

            // Проверяем, был ли выбран файл, если нет то прерываем программу
            if (fileText == null)
            {
                return;
            }
            //==================================================================================================

            // Нужно подсчитать количество знаков табуляции. Так мы поймем сколько будет столбцов у будущего массива "price"
            int    rows    = fileText.GetUpperBound(0);
            int    columns = 0;
            string str     = fileText[0];
            string tab     = "\t";
            int    index   = 0;;

            while ((index = str.IndexOf(tab, index)) != -1)
            {
                columns++;
                index = index + tab.Length;
            }
            price = new string[rows, columns];
            //==================================================================================================

            // Заполняем массив данными
            for (int i = 0; i < rows; i++)
            {
                string[] temp = fileText[i].Split('\t');
                for (int j = 0; j < columns; j++)
                {
                    price[i, j] = temp[j];
                }
            }
            //==================================================================================================

            // Проверяем на нулевые цены ("0.00") и исключаем их, если таковые находятся
            for (int i = 0; i < rows; i++)
            {
                if (price[i, 5] == "0.00")
                {
                    price[i, 0] = "0";
                }
            }
            //==================================================================================================

            // Блок проверки наименований на наличие.
            // Наименования с нулевым количеством на складах (учитываются склад Северянин, Пушкарев и магазин) не будут попадать в прайс-лист
            string zero = "0.00";

            price[0, 0] = "0";

            if (fullPrice == false)
            {
                for (int i = 0; i < rows; i++)
                {
                    if (price[i, 7] == zero && price[i, 9] == zero && price[i, 11] == zero && price[i, 3] != "OUP ELT OL")
                    {
                        price[i, 0] = "0";
                    }
                }
            }
            // Это условие срабатывает если пользователь поставил галку в чек боксе "Полный прайс"
            else
            {
                string op = "OP!";
                string na = "NA!";
                for (int i = 0; i < rows; i++)
                {
                    if (price[i, 2].EndsWith(op) || price[i, 2].EndsWith(na) && price[i, 7] == zero && price[i, 9] == zero && price[i, 11] == zero)
                    {
                        price[i, 0] = "0";
                    }
                }
            }
            //==================================================================================================

            // Блок проверки наименований на "агентское вознаграждение".
            // Агентское соглашение не будет попадать в прайс-лист
            string agent = "агентское вознаграждение";

            for (int i = 0; i < rows; i++)
            {
                if (price[i, 14] != null && price[i, 14].ToLower().StartsWith(agent))
                {
                    price[i, 0] = "0";
                }
            }
            //==================================================================================================

            // Блок проверки групп товаров.
            // Если группа товаров равна группе из списка исключений, то такое наименование не будет попадать в прайс
            if (fullPrice == false)
            {
                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < exceptions.Length; j++)
                    {
                        if (price[i, 3] == exceptions[j])
                        {
                            price[i, 0] = "0";
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < exceptions.Length; j++)
                    {
                        if (price[i, 3] == exceptions[j])
                        {
                            price[i, 0] = "0";
                        }
                    }
                    if (price[i, 3] == "RELOD Ltd. (RUR)" || price[i, 3] == "RELOD LTD." || price[i, 3] == "SELT" && price[i, 7] == "0.00" && price[i, 9] == "0.00" && price[i, 11] == "0.00")
                    {
                        price[i, 0] = "0";
                    }
                }
            }
            //==================================================================================================

            // Блок переноса данных из массива price в итоговый priceList

            for (int i = 0; i < rows; i++)
            {
                if (price[i, 0] != "0")
                {
                    string warehouse;
                    string store;
                    double warehouseQTY = double.Parse(price[i, 7], culture) + double.Parse(price[i, 11], culture);
                    double storeQTY     = double.Parse(price[i, 9], culture);

                    if (warehouseQTY > 10)
                    {
                        warehouse = "Более 10 шт";
                    }
                    else if (warehouseQTY == 1)
                    {
                        warehouse = "Мало";
                    }
                    else
                    {
                        warehouse = warehouseQTY.ToString();
                    }

                    if (storeQTY > 10)
                    {
                        store = "Более 10 шт";
                    }
                    else if (storeQTY == 1)
                    {
                        store = "Мало";
                    }
                    else
                    {
                        store = storeQTY.ToString();
                    }

                    priceList.Add(new PriceModel
                    {
                        ISBN         = price[i, 1],                                     // присваиваем ISBN
                        Title        = price[i, 14],                                    // присваиваем Наименование
                        Price        = double.Parse(price[i, 6], culture),              // присваиваем Цену
                        VAT          = double.Parse(price[i, 4], culture),              // присваиваем НДС
                        Group        = price[i, 3],                                     // присваиваем Группу
                        QTYwarehouse = warehouse,                                       // присваиваем Количество на складах (Северянин + Пушкарев)
                        QTYstore     = store,                                           // присваиваем Количество в магазине
                        ShortTitle   = price[i, 2]                                      // присваиваем Краткое наименование
                    });
                }
            }

            // Сортируем наш прайс по полю ShortTitle
            priceList = priceList.OrderBy(item => item.ShortTitle).ToList();

            // Добавляем нумерацию
            int count = 1;

            foreach (PriceModel item in priceList)
            {
                item.Number = count;
                count++;
            }

            SaveAsExcel(priceList);
        }
예제 #9
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();
        }
예제 #10
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);
            }
        }
예제 #11
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();
        }
예제 #12
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();
        }
예제 #13
0
 public ActionResult UploadFile(int idIndividualPlan, HttpPostedFileBase file_Uploader)
 {
     WorkWithFile.UploadFile(System.IO.Path.GetFileName(file_Uploader.FileName), file_Uploader.InputStream);
     return(RedirectToAction("Index", "Home"));
 }
예제 #14
0
        /// <summary>
        /// Кластеризация FastDBScan
        /// </summary>
        /// <param name="path"></param>
        /// <param name="k"></param>
        /// <param name="eps"></param>
        /// <param name="minPTS"></param>
        /// <param name="t"></param>
        void UseOnlyFastDBScan(string path, int k, double eps, int minPTS, int t)
        {
            bool         check      = true;
            Stopwatch    dbscantime = new Stopwatch();
            Stopwatch    kmeantime  = new Stopwatch();
            List <Point> points     = new List <Point>(0);

            try
            {
                points             = WorkWithFile.GetPointFromFile(path);
                progressBar1.Value = 30;
            }

            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                check = false;
                progressBar1.Value = 0;
            }
            if (k > points.Count)
            {
                MessageBox.Show("Введенный параметр K больше чем количество точек в выбранном файле. Уменьшите К или выберите другой файл!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); check = false; progressBar1.Value = 0;
            }
            if (check)
            {
                kmeantime.Start();
                int[] clustering = kmeans.Cluster(points, k - 1, 0);
                progressBar1.Value = 50;

                for (int i = 0; i < points.Count; i++)
                {
                    points[i].cluster = clustering[i];
                }

                progressBar1.Value = 30;
                kmeantime.Stop();


                List <MyLib.Point> fordbscan = new List <MyLib.Point>(0);

                for (int i = 0; i < k; i++)
                {
                    int count = 0;
                    for (int j = 0; j < points.Count; j++)
                    {
                        if (points[j].cluster == i)
                        {
                            count++;
                        }
                    }
                    int finalcount = (int)Math.Ceiling((double)count * t / 100);
                    int l          = 0;
                    for (int m = 0; m < points.Count; m++)
                    {
                        if (points[m].cluster == i && l < finalcount)
                        {
                            fordbscan.Add(points[m]); l++;
                        }
                    }
                }
                progressBar1.Value = 70;

                dbscantime.Start();
                int count_db = dbscan.Clustering(fordbscan, eps, minPTS);
                GetFullPicture(fordbscan, k, count_db);

                progressBar1.Value = 80;

                dbscantime.Stop();

                MessageBox.Show("Количество точек: " + points.Count + "\n" + "Время выполнения K-means: " + kmeantime.Elapsed.Seconds + " сек." + "\n" + "Время выполнения DBScan: " + dbscantime.Elapsed.Seconds + " сек." + "\n" + "Общее время выполнения: " + (kmeantime.Elapsed.Seconds + dbscantime.Elapsed.Seconds) + " сек." + "\n" + "Скорость выполнения: " + $"{((kmeantime.Elapsed.Seconds + dbscantime.Elapsed.Seconds > 0) ? (points.Count / (kmeantime.Elapsed.Seconds + dbscantime.Elapsed.Seconds)) : points.Count):F2} точки в сек.", "Время выполнения", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Graph.Graphic f1 = new Graph.Graphic(points, k, kmeantime, dbscantime, "Алгоритм кластеризации FastDbscan без ипользования R*-дерева");
                progressBar1.Value = 100;
                f1.Show();
            }
        }
예제 #15
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);
            }
        }
예제 #16
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();
        }
예제 #17
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();
        }