Clicky

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

Обновлено 3 weeks ago от Yelena

Статьи по теме

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

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

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

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

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

Selenium в Multilogin

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

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

  1. Перейдите в папку C:\Users\%username%\.multiloginapp.com и откройте файл app.properties в любом текстовом редакторе.
  2. Добавьте в файл следующую строку: multiloginapp.port=[PORT_NUMBER].
Номер порта должен находиться в диапазоне от 10000 до 49151.
  1. Сохраните файл app.properties.

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

Инструкции для начала работы на различных ОС вы можете найти в нашем руководстве.

Пример на 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 | Scale Fast With 1000s Of Profiles",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.chromium.options import ChromiumOptions
from selenium.webdriver.firefox.options 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()
print(json)

#Instantiate the Remote Web Driver to connect to the browser profile launched by previous GET request
# In case of using Mimic browser
driver = webdriver.Remote(command_executor=json['value'], options=ChromiumOptions())

# In case of using Stealthfox browser
#driver = webdriver.Remote(command_executor=json['value'], options=Options())

#Perform automation
driver.get('https://multilogin.com/')
print(driver.title)
driver.quit()
Видео по теме


Наши новости, полезные статьи и советы вы найдёте здесь


Вам удалось решить проблему?