B4J Library Selenium Library - Pnd_Selenium

Selenium automates browsers. That's it!
What you do with that power is entirely up to you.
Primarily it is for automating web applications for testing purposes, but is certainly not limited to just that.
Boring web-based administration tasks can (and should) also be automated as well.

Library can be used in UI and Console (Non-UI) app.

Wrapper is based on Selenium Java v4.33.0 (23. May 2025.) from HERE.


Some things Selenium can do:
  • Most importantly, it "sees" the web page the same way a user does, with CSS, JavaScript, etc.
  • Crawl or scrape websites, particularly those that don't provide an API and load content lazily using JavaScript.
  • Measure web page elements and determine their locations.
  • Simulate geolocation.
  • Collect virtually anything imaginable from web pages.
  • Inject JavaScript into a page, execute it, and retrieve the result.
  • Manipulates cookies: read, add, edit, delete.
  • Convert HTML to PDF.
  • Take screenshots of the "visible" part or the entire web page.
  • Can control web browser by automating user interactions, such as clicks, typing, scrolling, etc.
  • It's primarily used for functional and regression testing of web applications, ensuring they behave as expected when users interact with them.
  • You can use Selenium to extract information from web pages. It interacts with dynamic web content (JavaScript-heavy sites) better than traditional web scraping methods.
  • Can simulate complex user interactions like dragging and dropping, mouse hover, multi-click, or keyboard input (e.g., filling out forms).
  • You can fill out forms and submit them automatically, useful for testing forms or bulk form submissions.
  • Can interact with browser alerts, pop-ups, and other modal dialogs, accepting, dismissing, or retrieving messages.
  • It can interact with dynamic content that changes after page loads using techniques like waits, handling AJAX calls, or waiting for elements to load.
  • Can interact with file upload controls, uploading files as part of automated tests, and downloading files to verify download functionality.
  • Can run tests on headless browsers (browsers without a graphical user interface), such as Headless Chrome, enabling faster test execution, especially in CI/CD pipelines.
  • Allows you to start and stop browser sessions, making it easy to manage the browser lifecycle during test execution.
  • And much, much more.


Versions:

v1.05

  • Update for Selenium Java to v4.31.0

v1.06
  • Update for Selenium Java to v4.32.0

v1.07
  • Update for Selenium Java to v4.33.0


Examples:



Download library from: https://mega.nz/file/UF5XkCQI#uvA_q_ekRwLJVqJI6vTt1PiNgaOfRubjwuUwCKYkmas

To compile app in release mode with #MergeLibraries: True, please check Selenium15 example.
To build standalone package, please check Selenium16 example.

When you download Chrome for Testing as well as the Chrome Driver, make sure to extract everything into one folder.
chrome.exe and chromedriver.exe should be in same folder.
For Windows use:
Chrome For Testing: https://storage.googleapis.com/chrome-for-testing-public/137.0.7151.70/win64/chrome-win64.zip
Chrome Driver: https://storage.googleapis.com/chrome-for-testing-public/137.0.7151.70/win64/chromedriver-win64.zip

If you are using other OS download Chrome for Testing and Chrome Driver from: https://googlechromelabs.github.io/chrome-for-testing/
Latest library version is tested with Chrome for Testing and Chrome Driver v137.0.7151.70
 

Attachments

  • SeleniumExamples.zip
    51.2 KB · Views: 197
Last edited:

behnam_tr

Active Member
Licensed User
Longtime User
thank you man the excutescript is ok
can i send key combinations like ctrl+a with ActionSendNonTextKey ??
 

behnam_tr

Active Member
Licensed User
Longtime User
Thank you for the application library, is it possible to add methods to manage cookies?

 

Pip

Member
Hi Pendrush,

I have been able to work around the "Access-Denied" problem and am looking for a more elegant solution than the following to determine the currently installed Chrome version. The function will need to work on different systems.

Current working code:
B4X:
Try
    Selenium.AddArgument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0 Safari/537.36 Edg/115.0.1901.183")
    Selenium.Initialize("Selenium", "C:\B4J\Projects\UPS_test_selenium\chromedriver115.exe")
Catch
    Log(LastException)
End Try
    
Try
    Selenium.AddArgument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0 Safari/537.36")
    Selenium.Initialize("Selenium", "C:\B4J\Projects\UPS_test_selenium\chromedriver114.exe")
Catch
    Log(LastException)
End Try

It's unfortunately try and error code, is there any way to select the correct Chromedriver based on the installed version?

Kind regards
Pip
 

hanyelmehy

Well-Known Member
Licensed User
Longtime User
when try i get this error
B4X:
WARNING: package com.sun.javafx.embed.swing.oldimpl not in javafx.swing
Waiting for debugger to connect...
Program started.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Invalid port. Exiting...
Error occurred on line: 25 (Main)
org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Host info: host: 'DESKTOP-AI6L6HO', ip: '192.168.1.100'
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:561)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:229)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:157)
    at org.openqa.selenium.chromium.ChromiumDriver.<init>(ChromiumDriver.java:101)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:84)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:73)
    at com.pendrush.selenium.kotlin.SeleniumLib.initialize(SeleniumLib.kt:32)
    at com.pendrush.selenium.Wrapper.initialize2(Wrapper.java:39)
    at com.pendrush.selenium.Wrapper.Initialize(Wrapper.java:35)
    at b4j.example.main._appstart(main.java:81)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:629)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:237)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:167)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:111)
    at anywheresoftware.b4a.shell.ShellBA.raiseEvent2(ShellBA.java:100)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:98)
    at b4j.example.main.start(main.java:38)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: org.openqa.selenium.WebDriverException: Driver server process died prematurely.
Build info: version: '4.9.1', revision: 'eb2032df7f'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '14.0.1'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:242)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:114)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
    ... 34 more
 

pixet

Member
Licensed User
Longtime User
Last edited:

Pendrush

Well-Known Member
Licensed User
Longtime User

I will add Cookies in next few days.
I made an update to the library to ensure Selenium works. There has been a change in how Selenium interacts with the Chrome browser. Check post #1.
 

Magma

Expert
Licensed User
Longtime User
Hi there...

This is great !!!
I ve tested and works perfect - but there are sites with ultra-super-security... for example:

There are sites like price watcher for products that have robot-checker and can't bypass them...

or for example the Google search, always change the id of elements... how can you - use selenium on those sites, is it possible ?
 

Pendrush

Well-Known Member
Licensed User
Longtime User
There are sites like price watcher for products that have robot-checker and can't bypass them...
Check Selenium03 example and read comments inside.

or for example the Google search, always change the id of elements... how can you - use selenium on those sites, is it possible ?
Never used Selenium to scrape something from Google, but you can search online... Maybe someone have solution.
For sure you can use FindByTagNameList to get all tags.
 

Pendrush

Well-Known Member
Licensed User
Longtime User
or for example the Google search, always change the id of elements...

This code work as it should on Google Search:

B4X:
#Region Project Attributes
    #MainFormWidth: 400
    #MainFormHeight: 200
    #MergeLibraries: False
#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private Selenium As Pnd_Selenium
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    Sleep(500) ' To show MainForm before Chrome
         
    Dim UserAgent As String = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
    Selenium.AddArgument("--disable-blink-features=AutomationControlled")
    Selenium.AddArgument("--user-agent=" & UserAgent)
    Selenium.AddExperimentalOption("useAutomationExtension", False)
    Selenium.AddExperimentalOption("excludeSwitches", Array As String("enable-automation"))
    Selenium.Initialize("Selenium", "e:\Kotlin\Wrap_Selenium\ChromeForTestingAndChromeDriver\chromedriver.exe")
    Selenium.ExecuteScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})", "")
    Dim Parameters As Map = CreateMap("userAgent":UserAgent)
    Selenium.ExecuteCdpCommand("Network.setUserAgentOverride", Parameters)
    Selenium.NavigateTo("https://www.google.com/search?q=b4x")
End Sub

Sub Selenium_NavigationFinished
    Dim TagAlist As List = Selenium.FindByTagNameList("a")
    For Each TagA As Pnd_WebElement In TagAlist
        Log(TagA.GetText & " - " & TagA.GetDomProperty("href"))
    Next
    Sleep(2000)
    Selenium.Quit
    Sleep(1000)
    ExitApplication
End Sub
 

Magma

Expert
Licensed User
Longtime User
sharing my example:
 

MicroDrie

Well-Known Member
Licensed User
Longtime User
is there any way to bypass captcha?...
From Wikipedia:
An effective and evaluative security measure used to keep "unwanted behavior out" and to prevent it from happening without "human consent". Considering those two security reasons, the answer is NO.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…