Браузерная автоматизация с Selenium

Последнее изменение:


Браузерная автоматизация с Selenium позволяет автоматизировать различные задачи браузерных профилей Indigo. Начиная от создания простых скриптов автоматизации и заканчивая веб-краулерами, которые ищут, собирают и взаимодействуют с данными.

Браузерная автоматизация Indigo основана на Selenium WebDriver.

Как правило, при обычной автоматизации с Selenium, вы прежде всего подключаетесь к Firefox (Gecko) или Chrome драйверу напрямую и устанавливаете desired capabilities. В случае с Indigo, вы используете Remote Web Driver для подключения к браузерному профилю через локальный порт, и устанавливаете desired capabilities для запуска команд в определённом браузерном профиле.

Поддерживаемые языки

Поскольку Selenium фреймворк поддерживает большое количество языков программирования, то и автоматизация с Indigo может быть написана на разных языках. Тем не менее мы предоставляем техническую поддержку только для скриптов написанных на Java и Python.

Определение порта Indigo

Чтобы использовать автоматизацию Selenium в Indigo, предварительно необходимо предопределить порт приложения.

  1. Перейдите в папку C:\Users\%username%\.indigobrowser и откройте файл app.properties в любом текстовом редакторе.
  2. Добавьте в файл следующую строку: multiloginapp.port=[PORT_NUMBER].

    Номер порта должен находиться в диапазоне от 10000 до 49151.

  3. Сохраните файл app.properties.

    В дальнейшем вы сможете обращаться к Indigo по данному порту.

    Пример на Java:

    import org.junit.Assert;
    import org.openqa.selenium.firefox.FirefoxOptions;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.json.JSONObject;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    public class BrowserProfile {
    public static void main(String[] args) throws Exception {
    BrowserProfile bp = new BrowserProfile();
    //TODO replace with existing profile ID. Define the ID of the browser profile, where the code will be executed.
    String profileId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    //Define DesiredCapabilities
    DesiredCapabilities dc = new DesiredCapabilities();
    //Instantiate the Remote Web Driver to connect to the browser profile launched by startProfile method
    RemoteWebDriver driver = new RemoteWebDriver(new URL(bp.startProfile(profileId)), dc);
    //Perform automation
    driver.get("https://multilogin.com/");
    Assert.assertEquals("Multilogin - Replace Multiple Computers With Virtual Browser Profiles - Multilogin",driver.getTitle());
    driver.quit();
    }
    private String startProfile(String profileId) throws Exception {
    /*Send GET request to start the browser profile by profileId. Returns response in the following format:
    '{"status":"OK","value":"http://127.0.0.1:XXXXX"}', where XXXXX is the localhost port on which browser profile is
    launched. Please make sure that you have Multilogin listening port set to 35000. Otherwise please change the port
    value in the url string*/
    String url = "http://127.0.0.1:35000/api/v1/profile/start?automation=true&profileId=" + profileId;
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
    }
    in.close();
    //Get JSON text from the response and return the value by key "value"
    JSONObject jsonResponse = new JSONObject(response.toString());
    return jsonResponse.getString("value");
    }
    }

    Пример на Python:

    from selenium import webdriver
    from selenium.webdriver.firefox import options
    import requests
    #TODO replace with existing profile ID. Define the ID of the browser profile, where the code will be executed.
    mla_profile_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
    mla_url = 'http://127.0.0.1:35000/api/v1/profile/start?automation=true&profileId='+mla_profile_id
    """
    Send GET request to start the browser profile by profileId. Returns response in the following format: '{"status":"OK","value":"http://127.0.0.1:XXXXX"}', where XXXXX is the localhost port on which browser profile is launched. Please make sure that you have Multilogin listening port set to 35000. Otherwise please change the port value in the url string
    """
    resp = requests.get(mla_url)
    json = resp.json()
    #Define DesiredCapabilities
    opts = options.DesiredCapabilities()
    #Instantiate the Remote Web Driver to connect to the browser profile launched by previous GET request
    driver = webdriver.Remote(command_executor=json['value'], desired_capabilities={})
    #Perform automation
    driver.get('https://multilogin.com/')
    assert "Multilogin - Replace Multiple Computers With Virtual Browser Profiles - Multilogin" in driver.title
    driver.quit()

    Эта статья помогла Вам?