Selenide java выбор браузера
Selenide supports only web based application, opening a browser for any operation is must. We cannot access already opened browser in selenide.
Opening a browser in selenide is so simple, we donot even have to create any object. What we have to do is just give a call to open() method and pass the url.
We have to be careful about the import statement, your IDE might not support automatic imports, Firefox is the default browser
Open Chrome browser in Selenide
By default Selenide opens the Firefox, to open any other browser we have to explicitly mention the driver executable path to System property.
And set the selenide.browser to chrome, after setting the executable and browser name call open() method with parameter.
Open Internet Explorer in Selenide
We can open IE browser with selenide, to open IE browser we have to set the IEdriverserver.exe and the browser name to Internet Explorer
Close browser in Selenide
We donot have to close the browser as the selenide takes care of the closing browser after the test execution. But If you want close before execution you can use close() method
Work offline in Selenide
Sometime we may not have internet but we may be in practice phase, in those kind of scenarios we can use selenide to work with offline web application.
Note: If the site doesnot have the the protocol then just copy paste the url into eclipse it will automatically imports the protocol.
Get Title in Selenide
We can get title of webpage using title() method in selenide, below image shows where the page title present in the source code
Get Url Of the page in Selenide
We can get the url of the page using url() method.
Get source code Of the page in Selenide
We can get the source code of the page using source() method.
Navigation Commands in selenide
Navigation commands are some which enables the user to navigate to through history like back, forth, refresh.
Below are the few Commands:
1. refresh()
2. back()
3. forward()
1. refresh() : refresh() method refreshes the current page
2. back() : back method helps the user to navigate back.
In above program you might not face any error but it also will not navigate anywhere ,why ? because back() calls the back() native method present in the browser indirectly so it works only when you navigate more than one page.Then only the button on the browser will be enabled unless it enabled the back() method never works.
Modify the above program like below one
Important Note : Notice that when we used open() method for second time, selenide doesnot open new browser, it just naviagtes to new url.
3. Forward() : The forward() method navigates the user to forth but if we want forward() method to work we should use back() before using forward() then only the forward button in browser is enabled
You can also share knowledge by Adding a topic here
report this ad
Мотивация
Почему недостаточно Selenium webdriver
Зачем понадобилась ещё одна обёртка над Selenium?
Page Objects
Можно ли использовать Пэдж Обжекты с Selenide?
Да! Вы можете использовать Пэдж Обжекты с Selenide.
Более того, с Selenide ваши page objects станут короче и читабельнее. Тут подробности.
Настройки
Где я могу найти все доступные настройки Selenide?
Описание всех настроек и значений по умолчанию можно найти в javadoc.
Selenide имеет очень разумные настройки по умолчанию, которые должны быть удобны для большинства “нормальных” проектов.
Но если всё-таки захочется запустить тесты с другими настройками, это можно сделать либо через System property:
либо программно, прямо в тестах:
Браузеры
Можно ли запустить тесты Selenide на Internet Explorer? А headless-браузере?
Да. Selenide можно запускать с любым браузером, для которого существует webdriver. Самые популярные браузеры поддерживаются из коробки (chrome, firefox, edge, ie, safari, opera). Некоторые менее популярные тоже поддерживаются, но требуют пары строк конфигурации (phantomjs, htmlunit). См. Wiki.
Другие браузеры тоже можно использовать, передав имя класса вебдрайвера.
Например, чтобы запустить тесты с браузером Firefox: -Dselenide.browser=firefox
Как сказать Selenide использовать браузер с моим кастомным профайлом?
Вы можете подсунуть Selenide любой экземпляр webdriver, который вы можете создать с какими угодно параметрами. Смотри примеры на Wiki.
Можно ли использовать Selenide в связке с Selenium Grid?
Можно ли использовать Selenide в связке с Selenoid?
Можно ли использовать Selenide для тестирования мобильных приложений?
Да, Selenide поддерживает тестирование мобильных приложений с помощью библиотеки Appium.
- Мы рекомендуем использовать селенидовский плагин selenide-appium.
- Вы можете найти рабочие примеры на гитхабе
- Посмотрите презентацию Selenide для мобилок
Билд-скрипты
Как запустить тесты Selenide на CI - сервере непрерывной интеграции?
Для этого нужно написать билд-скрипт. Скорее всего он у вас уже есть. На Wiki page есть несколько примеров на Ant и Gradle.
Скриншоты (снимок экрана)
Как сказать Selenide сохранять скриншоты в другую папку?
Вкладки/окна браузера
Как переключаться между разными окошками / вкладками браузера?
Для этого можно использовать API самого Selenium WebDriver.
- getWebDriver().getWindowHandles() - возвращает множество всех вкладок или окон
- getWebDriver().getWindowHandle() - возвращает уникальный идентификатор активной вкладки или окна.
Исходный код Selenide
Могу ли я посмотреть исходный код Selenide?
Да. Исходный код Selenide выложен на гитхабе.
Могу ли я вносить изменения в Selenide?
Конечно! На то он и open source. Если умеете кодить сами, смело создавайте Pull Request, если нет - оформляйте свои пожелалки в виде issue.
Лицензия
Если наш заказчик потребует исходный код тестов, позволяет ли лицензия Selenide ему их передать?
Selenide - бесплатный продукт с открытым исходным кодом, распространяемый по лицензии MIT. Проще говоря, это значит, что вы можете делать с ним всё что угодно.
Configuration settings for Selenide default browser
This class is designed so that every setting can be set either via system property or programmatically.
Please note that all fields are static, meaning that every change will immediately reflect in all threads (if you run tests in parallel).
These system properties can be additonally used having effect on every new created browser in test. For example as -D
chromeoptions.args - Sets the arguments for chrome options, parameters are comma separated If comma is a part of the value, use double quotes around the argument Non-official list of parameters can be found at https://peter.sh/experiments/chromium-command-line-switches/ Example: --no-sandbox,--disable-3d-apis,"--user-agent=Firefox 45, Mozilla"
chromeoptions.prefs - ser the preferences for chrome options, which are comma separated keyX=valueX preferences. If comma is a part of the value, use double quotes around the preference List of preferences can be found at https://chromium.googlesource.com/chromium/src/+/master/chrome/common/pref_names.cc Example: homepage=http://google.com,"intl.allowed_languages=en,ru,es"
Field Summary
Base url for open() function calls Can be configured either programmatically or by system property "-Dselenide.baseUrl=http://myhost".
If set to true, sets value by javascript instead of using Selenium built-in "sendKey" function (that is quite slow because it sends every character separately).
Interval in milliseconds, when checking if a single element or collection elements are appeared Can be configured either programmatically or by system property "-Dselenide.pollingInterval=50"
Default value: 200 (milliseconds)
Timeout in milliseconds to fail the test, if conditions still not met Can be configured either programmatically or by system property "-Dselenide.timeout=10000"
Default value: 4000 (milliseconds)
If set to true, 'setValue' and 'val' methods of SelenideElement can work as 'selectOptionByValue', 'selectRadio' depending on the real control type, defined by element's tag.
Constructor Summary
Method Summary
Methods inherited from class java.lang.Object
Field Detail
baseUrl
timeout
Timeout in milliseconds to fail the test, if conditions still not met Can be configured either programmatically or by system property "-Dselenide.timeout=10000"
Default value: 4000 (milliseconds)
pollingInterval
Interval in milliseconds, when checking if a single element or collection elements are appeared Can be configured either programmatically or by system property "-Dselenide.pollingInterval=50"
Default value: 200 (milliseconds)
holdBrowserOpen
If holdBrowserOpen is true, browser window stays open after running tests. It may be useful for debugging. Can be configured either programmatically or by system property "-Dselenide.holdBrowserOpen=true".
Default value: false.
reopenBrowserOnFail
Should Selenide re-spawn browser if it's disappeared (hangs, broken, unexpectedly closed).
Can be configured either programmatically or by system property "-Dselenide.reopenBrowserOnFail=false".
Set this property to false if you want to disable automatic re-spawning the browser.
Default value: true
browser
Which browser to use. Can be configured either programmatically or by system property "-Dselenide.browser=ie". Supported values: "chrome", "firefox", "legacy_firefox", "ie", "htmlunit", "phantomjs", "opera", "safari", "edge", "jbrowser"
Default value: "chrome"
browserVersion
Which browser version to use (for Internet Explorer). Can be configured either programmatically or by system property "-Dselenide.browserVersion=8".
Default value: none
remote
URL of remote web driver (in case of using Selenium Grid). Can be configured either programmatically or by system property "-Dselenide.remote=http://localhost:5678/wd/hub".
Default value: null (Grid is not used).
browserSize
The browser window size. Can be configured either programmatically or by system property "-Dselenide.browserSize=1024x768".
Default value: 1366x768
browserPosition
The browser window position on screen. Can be configured either programmatically or by system property "-Dselenide.browserPosition=10x10".
Default value: none
startMaximized
The browser window is maximized when started. Can be configured either programmatically or by system property "-Dselenide.startMaximized=true".
Default value: false
browserCapabilities
Browser capabilities. Warning: this capabilities will override capabilities were set by system properties.
Default value: DesiredCapabilities::new
pageLoadStrategy
clickViaJs
ATTENTION! Automatic WebDriver waiting after click isn't working in case of using this feature. Use clicking via JavaScript instead common element clicking. This solution may be helpful for testing in Internet Explorer. Can be configured either programmatically or by system property "-Dselenide.clickViaJs=true".
Default value: false
screenshots
Defines if Selenide takes screenshots on failing tests. Can be configured either programmatically or by system property "-Dselenide.screenshots=false".
Default value: true
savePageSource
Defines if Selenide saves page source on failing tests. Can be configured either programmatically or by system property "-Dselenide.savePageSource=false".
Default value: true
reportsFolder
Folder to store screenshots to. Can be configured either programmatically or by system property "-Dselenide.reportsFolder=test-result/reports".
Default value: "build/reports/tests" (this is default for Gradle projects)
reportsUrl
Optional: URL of CI server where reports are published to. In case of Jenkins, it is "BUILD_URL/artifact" by default.
Can be configured either programmatically or by system property "-Dselenide.reportsUrl=http://jenkins-host/reports".
If it's given, names of screenshots are printed as "http://ci.mycompany.com/job/my-job/446/artifact/build/reports/tests/my_test.jpg" - it's useful to analyze test failures in CI server.
fastSetValue
If set to true, sets value by javascript instead of using Selenium built-in "sendKey" function (that is quite slow because it sends every character separately).
Tested on Codeborne projects - works well, speed up ~30%. Some people reported 150% speedup (because sending characters one-by-one was especially slow via network to Selenium Grid on cloud).
https://github.com/codeborne/selenide/issues/135 Can be configured either programmatically or by system property "-Dselenide.fastSetValue=true".
Default value: false
versatileSetValue
If set to true, 'setValue' and 'val' methods of SelenideElement can work as 'selectOptionByValue', 'selectRadio' depending on the real control type, defined by element's tag.
Will decrease performance of setValue, make it slower, but will also make tests implementation more "business oriented". With this property being set to true, tests may no longer be dependent on actual control implementation in html and be more abstract.
https://github.com/codeborne/selenide/issues/508 Can be configured either programmatically or by system property "-Dselenide.versatileSetValue=true".
Default value: false
selectorMode
assertionMode
fileDownload
proxyEnabled
If Selenide should run browser through its own proxy server. It allows some additional features which are not possible with plain Selenium. But it's not enabled by default because sometimes it would not work (more exactly, if tests and browser and executed on different machines, and "test machine" is not accessible from "browser machine"). If it's not your case, I recommend to enable proxy. Can be configured either programmatically or by system property "-Dselenide.proxyEnabled=true"
Default: false
proxyHost
Host of Selenide proxy server. Used only if proxyEnabled == true. Can be configured either programmatically or by system property "-DproxyHost=127.0.0.1"
Default: empty (meaning that Selenide will detect current machine's ip/hostname automatically)
proxyPort
Port of Selenide proxy server. Used only if proxyEnabled == true. Can be configured either programmatically or by system property "-Dselenide.proxyPort=8888"
Default: 0 (meaning that Selenide will choose a random free port on current machine)
driverManagerEnabled
Controls Selenide and WebDriverManager integration. When integration is enabled you don't need to download and setup any browser driver executables. See https://github.com/bonigarcia/webdrivermanager for WebDriverManager configuration details. Can be configured either programmatically or by system property "-Dselenide.driverManagerEnabled=false"
Default: true
headless
Enables the ability to run the browser in headless mode. Works only for Chrome(59+) and Firefox(56+). Can be configured either programmatically or by system property "-Dselenide.headless=true"
Default: false
browserBinary
Sets the path to browser executable. Works only for Chrome, Firefox and Opera. Can be configured either programmatically or by system property "-Dselenide.browserBinary=/path/to/binary"
Configuration settings for Selenide default browser
This class is designed so that every setting can be set either via system property or programmatically.
Please note that all fields are static, meaning that every change will immediately reflect in all threads (if you run tests in parallel).
These system properties can be additonally used having effect on every new created browser in test. For example as -D
chromeoptions.args - Sets the arguments for chrome options, parameters are comma separated If comma is a part of the value, use double quotes around the argument Non-official list of parameters can be found at https://peter.sh/experiments/chromium-command-line-switches/ Example: --no-sandbox,--disable-3d-apis,"--user-agent=Firefox 45, Mozilla"
chromeoptions.prefs - Sets the preferences for chrome options, which are comma separated keyX=valueX preferences. If comma is a part of the value, use double quotes around the preference List of preferences can be found at https://chromium.googlesource.com/chromium/src/+/master/chrome/common/pref_names.cc Example: homepage=http://google.com,"intl.allowed_languages=en,ru,es"
Field Summary
Base url for open() function calls Can be configured either programmatically or by system property "-Dselenide.baseUrl=http://myhost".
If set to true, sets value by javascript instead of using Selenium built-in "sendKey" function (that is quite slow because it sends every character separately).
Interval in milliseconds, when checking if a single element or collection elements are appeared Can be configured either programmatically or by system property "-Dselenide.pollingInterval=50"
Default value: 200 (milliseconds)
Timeout in milliseconds to fail the test, if conditions still not met Can be configured either programmatically or by system property "-Dselenide.timeout=10000"
Default value: 4000 (milliseconds)
If set to true, 'setValue' and 'val' methods of SelenideElement can work as 'selectOptionByValue', 'selectRadio' depending on the real control type, defined by element's tag.
Constructor Summary
Method Summary
Methods inherited from class java.lang.Object
Field Detail
baseUrl
timeout
Timeout in milliseconds to fail the test, if conditions still not met Can be configured either programmatically or by system property "-Dselenide.timeout=10000"
Default value: 4000 (milliseconds)
pollingInterval
Interval in milliseconds, when checking if a single element or collection elements are appeared Can be configured either programmatically or by system property "-Dselenide.pollingInterval=50"
Default value: 200 (milliseconds)
holdBrowserOpen
If holdBrowserOpen is true, browser window stays open after running tests. It may be useful for debugging. Can be configured either programmatically or by system property "-Dselenide.holdBrowserOpen=true".
Default value: false.
reopenBrowserOnFail
Should Selenide re-spawn browser if it's disappeared (hangs, broken, unexpectedly closed).
Can be configured either programmatically or by system property "-Dselenide.reopenBrowserOnFail=false".
Set this property to false if you want to disable automatic re-spawning the browser.
Default value: true
browser
Which browser to use. Can be configured either programmatically or by system property "-Dselenide.browser=ie". Supported values: "chrome", "firefox", "legacy_firefox" (upto ESR 52), "ie", "opera", "edge"
Default value: "chrome"
browserVersion
Which browser version to use (for Internet Explorer). Can be configured either programmatically or by system property "-Dselenide.browserVersion=8".
Default value: none
remote
URL of remote web driver (in case of using Selenium Grid). Can be configured either programmatically or by system property "-Dselenide.remote=http://localhost:5678/wd/hub".
Default value: null (Grid is not used).
browserSize
The browser window size. Can be configured either programmatically or by system property "-Dselenide.browserSize=1024x768".
Default value: 1366x768
browserPosition
The browser window position on screen. Can be configured either programmatically or by system property "-Dselenide.browserPosition=10x10".
Default value: none
startMaximized
The browser window is maximized when started. Can be configured either programmatically or by system property "-Dselenide.startMaximized=true".
Default value: false
browserCapabilities
Browser capabilities. Warning: this capabilities will override capabilities were set by system properties.
Default value: DesiredCapabilities::new
pageLoadStrategy
clickViaJs
ATTENTION! Automatic WebDriver waiting after click isn't working in case of using this feature. Use clicking via JavaScript instead common element clicking. This solution may be helpful for testing in Internet Explorer. Can be configured either programmatically or by system property "-Dselenide.clickViaJs=true".
Default value: false
screenshots
Defines if Selenide takes screenshots on failing tests. Can be configured either programmatically or by system property "-Dselenide.screenshots=false".
Default value: true
savePageSource
Defines if Selenide saves page source on failing tests. Can be configured either programmatically or by system property "-Dselenide.savePageSource=false".
Default value: true
reportsFolder
Folder to store screenshots to. Can be configured either programmatically or by system property "-Dselenide.reportsFolder=test-result/reports".
Default value: "build/reports/tests" (this is default for Gradle projects)
reportsUrl
Optional: URL of CI server where reports are published to. In case of Jenkins, it is "BUILD_URL/artifact" by default.
Can be configured either programmatically or by system property "-Dselenide.reportsUrl=http://jenkins-host/reports".
If it's given, names of screenshots are printed as "http://ci.mycompany.com/job/my-job/446/artifact/build/reports/tests/my_test.jpg" - it's useful to analyze test failures in CI server.
fastSetValue
If set to true, sets value by javascript instead of using Selenium built-in "sendKey" function (that is quite slow because it sends every character separately).
Tested on Codeborne projects - works well, speed up ~30%. Some people reported 150% speedup (because sending characters one-by-one was especially slow via network to Selenium Grid on cloud).
https://github.com/codeborne/selenide/issues/135 Can be configured either programmatically or by system property "-Dselenide.fastSetValue=true".
Default value: false
versatileSetValue
If set to true, 'setValue' and 'val' methods of SelenideElement can work as 'selectOptionByValue', 'selectRadio' depending on the real control type, defined by element's tag.
Will decrease performance of setValue, make it slower, but will also make tests implementation more "business oriented". With this property being set to true, tests may no longer be dependent on actual control implementation in html and be more abstract.
https://github.com/codeborne/selenide/issues/508 Can be configured either programmatically or by system property "-Dselenide.versatileSetValue=true".
Default value: false
selectorMode
assertionMode
fileDownload
proxyEnabled
If Selenide should run browser through its own proxy server. It allows some additional features which are not possible with plain Selenium. But it's not enabled by default because sometimes it would not work (more exactly, if tests and browser and executed on different machines, and "test machine" is not accessible from "browser machine"). If it's not your case, I recommend to enable proxy. Can be configured either programmatically or by system property "-Dselenide.proxyEnabled=true"
Default: false
proxyHost
Host of Selenide proxy server. Used only if proxyEnabled == true. Can be configured either programmatically or by system property "-DproxyHost=127.0.0.1"
Default: empty (meaning that Selenide will detect current machine's ip/hostname automatically)
proxyPort
Port of Selenide proxy server. Used only if proxyEnabled == true. Can be configured either programmatically or by system property "-Dselenide.proxyPort=8888"
Default: 0 (meaning that Selenide will choose a random free port on current machine)
driverManagerEnabled
Controls Selenide and WebDriverManager integration. When integration is enabled you don't need to download and setup any browser driver executables. See https://github.com/bonigarcia/webdrivermanager for WebDriverManager configuration details. Can be configured either programmatically or by system property "-Dselenide.driverManagerEnabled=false"
Default: true
headless
Enables the ability to run the browser in headless mode. Works only for Chrome(59+) and Firefox(56+). Can be configured either programmatically or by system property "-Dselenide.headless=true"
Default: false
browserBinary
Sets the path to browser executable. Works only for Chrome, Firefox and Opera. Can be configured either programmatically or by system property "-Dselenide.browserBinary=/path/to/binary"
помогите с такой проблемой: в селениум (JUnit) я понял как заставить его открывать оперу, а в селениде не знаю как это сделать, а он при попытке открыть сайт выдаёт Cannot find firefox binary in PATH. Make sure firefox is installed. Вот собственно и всё. Вопрос в целом как и где в селениде прописывать браузер. Спасибо!
2 ответа 2
Добавьте в ран конфигурацию -Dselenide.browser=YOUR_BROWSER где YOUR_BROWSER может принимать одно из значений: chrome , firefox , ie , phantomjs , htmlunit , safari , opera .
Ну и системное свойство, хранящее путь к исполняемому файлу выбранного вебдрайвера, тоже надо не забыть установить.
В коде выбрать браузер можно таким образом:
В идее делаем так:
- Запускаем тест (это сгенерит дефолтную ран-конфигурацию)
- Идем сюда:
В Вашем случае в левом кружке будет название Вашего класса и метода.
Подскажите, где это писать -Dselenide.browser=YOUR_BROWSER, что за ран конфигурация? В инете просто сразу показывают возможности селенида, без того как его настроить.
Intelegy IDEA.. Заменил в мавене на более позднюю зависимость селенида, сработала команда WebDriverRunner.setWebDriver(operaDriver);
Спасибо большое, исчерпывающе, нигде про это не видел. Единственное: Configuration.browser = "opera"; все равно не работает, после точки нету 'browser'. Т.е. в коде менять не могу.
Из гита: To run Selenide with any other web browser driver, just pass name of it's class to "browser" parameter: java -Dselenide.browser=org.openqa.selenium.firefox.FirefoxDriver значит тут я не понял запись, Dselenid горит красным, вообще синтаксис этой записи не понял, может объясните? Another option is to directly say Selenide use your desired WebDriver instance: WebDriverRunner.setWebDriver(myWebDriver). здесь тоже прикольно - после точки нет метода сетдрайвер, только гет. Может что не импортировал? Спасибо за помощь.
Всё ещё ищете ответ? Посмотрите другие вопросы с метками selenium-webdriver junit selenide или задайте свой вопрос.
Похожие
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.5.10.42086
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Читайте также: