How to collect information from Contour. Purchasing with Selenium

  • Tutorial
Hello.

This story happened because of savings. When buying a paid account, we didn’t even pay attention to how much the Expert tariff gives.

Oh, if we paid attention to this, I would not have to master Selenium and the basics of Java.

Once, a marketing task arose - to collect the contacts of purchasers in companies on our subject.

I am looking for all contests that are suitable for keywords and in the right regions. For all past years, completed and current.

In the unloading at the Standard tariff, here is the data:



There is only the name of the company. There is no contact information for the purchaser.

Now, in order not to manually collect the contact details of the purchaser, I decide to write a script.

Since Kontur.Zakupok the whole page is loaded with javascript, then you can’t get off with simple parsing. We'll have to write a script on Selenium.

To begin with, we will prepare the initial data - we save the contest number in CSV (the same parameter in the URL), as well as the company name, so as not to parse it. All this in the file kontur_getContacts_src.csv



Further, the Java script with comments

import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.io.*;
import java.nio.file.*;
publicclasskontur_getContacts{
	publicstaticvoidmain(String args[])throws Exception{
		//Запускаем коннектор к FireFox
		System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
		FirefoxDriver driver = new FirefoxDriver();// Create a Firefox browser instance
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		// Логинимся в Контур.Закупки		
		driver.get("https://auth.kontur.ru/login.aspx?authmode=certlogin&back=https%3A%2F%2Fzakupki.kontur.ru%2FLogin%2FCallback%3FReturnUrl%3Dhttps%253A%252F%252Fzakupki.kontur.ru%252F%253Fevent-login%253D1&customize=zakupki"); //Открываем страничку логина
		Thread.sleep(2*1000);
		WebElement login_field = driver.findElement(By.cssSelector(".loginPassword__login input")); // Ищем поле логин
		login_field.sendKeys("sales@mycomp.ru");//Посылаем текст элементу логин
		WebElement pass_field = driver.findElement(By.cssSelector("input.input__realInput")); //Ищем поле Пароль
		pass_field.sendKeys("password");//Посылаем текст элементу пароль
		Thread.sleep(1*1000); //Жду
		driver.findElement(By.cssSelector("input.button__input")).click(); // Ставлю галочку Оставаться в системе
		Thread.sleep(1*1000); //Жду
		driver.findElement(By.cssSelector(".loginPassword__submit .button__input")).click(); //Отправляю форму
		Thread.sleep(2*1000); //Жду
		String sourceFilePath = "C:/Users/user/selenium/kontur_getContacts_src.csv";//Файл, откуда брать исходную информацию
		String resultFilePath = "C:/Users/user/selenium/kontur_getContacts_result.csv";//Файл, куда писать результаты
		String delimeter = ";"; // Разделитель в файле с исходной информацией//Объявляем переменные
		String name; String text; 
		Integer flag_hasName=0;
		Integer flag_oneVar=0;
		try{
			//Откроем файл с проектами
			FileInputStream fstream = new FileInputStream(sourceFilePath);
			BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
			String strLine;//Объявляем переменные
			String[] subStr;//Объявляем переменные//Очищаем результирующий файлbyte[] myBytes = "".getBytes(); 
			Files.write(Paths.get(resultFilePath), myBytes);
			while ((strLine = br.readLine()) != null){ //Читаем файл с исходными данными построчно
				System.out.println(strLine); //Смотрим в консоли текущуб строку//Делим текущую строку по делимитеру	 
				subStr = strLine.split(delimeter);
				System.out.println("Found order_id "+subStr[0]+" and Organization is "+subStr[1]);
				//Открываем страничку с этой закупкой
				driver.get("https://zakupki.kontur.ru/"+subStr[0]);
				/* Находим первую ссылочку на контакт закупщика */
				name =""; //Очищаем переменную, в кот будет имя заказчика
				text =""; //Очищаем переменную, в кот будут результаты работы скрипта
				List<WebElement> tenderField_data_in=driver.findElements(By.cssSelector(".popup__mainContacts .tenderField__s div.tenderField_data_in")); //Находим первую ссылкуif(tenderField_data_in.size()>0){ 
					WebElement man = driver.findElement(By.cssSelector(".popup__mainContacts .tenderField__s div.tenderField_data_in"));//Находим поле имя
					System.out.println("FOUND is "+man.getAttribute("textContent")); //Смотрим имя в консоли
					name = man.getAttribute("textContent").trim(); //Присваиваем имя переменной name
				}
				// Ищем ссылки с данными заказчика
				List<WebElement> elements = driver.findElements(By.cssSelector(".tenderField .tenderField_data_in a"));
				System.out.println("Count elements in array is "+elements.size()); //Смотрим в консоли количество найденных элементов данныхif(elements.size()>0){ //Есть линки на странице
					WebElement email = driver.findElement(By.cssSelector(".tenderField .tenderField_data_in a")); //Выделяем емейл
					text=subStr[1]+delimeter+email.getAttribute("href")+delimeter+name+"\r\n"; // Формируем строку для записи в файл с результатами
					Files.write(Paths.get(resultFilePath), text.getBytes(), StandardOpenOption.APPEND); //Дописываем в файл
				} 
		   }
		}catch (IOException e){
		   System.out.println("Error opening or processing file with finished purchases");
		}
		// Close the browser instance
		driver.quit();
	}
}

Run the Selenium script. The result will be such a file with contacts that can be used for marketing purposes.

C:\Users\user\selenium>"C:\Program Files\Java\jdk-10.0.1\bin\javac" -cp selenium-server-standalone-3.13.0.jar; kontur_getContacts.java
* C:\Users\user\selenium>"C:\Program Files\Java\jre-10.0.1\bin\java" -cp selenium-server-standalone-3.13.0.jar; kontur_getContacts





Also popular now: