PS.Selenium.Modules 0.1.1

dotnet add package PS.Selenium.Modules --version 0.1.1
NuGet\Install-Package PS.Selenium.Modules -Version 0.1.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PS.Selenium.Modules" Version="0.1.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PS.Selenium.Modules --version 0.1.1
#r "nuget: PS.Selenium.Modules, 0.1.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PS.Selenium.Modules as a Cake Addin
#addin nuget:?package=PS.Selenium.Modules&version=0.1.1

// Install PS.Selenium.Modules as a Cake Tool
#tool nuget:?package=PS.Selenium.Modules&version=0.1.1

Selenium ✅ via ▶️ PowerShell

A small library of PowerShell modules using Selenium.

Automated deployment and updating of all dependencies (Chromium browser, Selenium and Chrome drivers) to be able to work with Selenium library using PowerShell language.

Modules with working examples can be found here ➡️ Selenium-Modules

🚀 To quickly install or update all drivers and chromium of the appropriate version, use the following command in your terminal:

Invoke-Expression(New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/Lifailon/Deploy-Selenium/rsa/Deploy-Selenium-Drivers.ps1")

📚 File composition:

PS C:\Users\lifailon\Documents\Selenium> Get-ChildItem

Directory: C:\Users\lifailon\Documents\Selenium

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          18.10.2023    12:39                chrome-win32
-a---          26.05.2023    18:39       12273664 chromedriver.exe
-a---          15.10.2023    16:47        4276224 WebDriver.dll
-a---          15.10.2023    16:47          33792 WebDriver.Support.dll

📑 Example connection and work

Example of connecting a set of drivers and working with selenium via PowerShell:

$path = "$home\Documents\Selenium\"
$log = "$path\ChromeDriver.log"
$ChromeDriver = "$path\ChromeDriver.exe"
$WebDriver = "$path\WebDriver.dll"
$SupportDriver = "$path\WebDriver.Support.dll"
$Chromium = (Get-ChildItem $path -Recurse | Where-Object Name -like chrome.exe).FullName
Add-Type -Path $WebDriver
Add-Type -Path $SupportDriver
try {
    $ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions # создаем объект с настройками запуска браузера
    $ChromeOptions.BinaryLocation = $Chromium # передаем путь до исполняемого файла, который отвечает за запуск браузера
    $ChromeOptions.AddArgument("start-maximized") # добавляем аргумент, который позволяет запустить браузер на весь экран
    $ChromeOptions.AcceptInsecureCertificates = $True # игнорировать предупреждение на сайтах с не валидным сертификатом
    #$ChromeOptions.AddArgument("headless") # скрывать окно браузера при запуске
    $ChromeDriverService = [OpenQA.Selenium.Chrome.ChromeDriverService]::CreateDefaultService($ChromeDriver) # создаем объект настроек службы драйвера
    $ChromeDriverService.HideCommandPromptWindow = $True # отключаем весь вывод логирования драйвера в консоль (этот вывод нельзя перенаправить)
    $ChromeDriverService.LogPath = $log # указать путь до файла с журналом
    $ChromeDriverService.EnableAppendLog = $True # не перезаписывать журнал при каждом новом запуске
    #$ChromeDriverService.EnableVerboseLogging = $True # кроме INFO и ошибок, записывать DEBUG сообщения
    $Selenium = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeDriverService, $ChromeOptions) # инициализируем запуск с указанными настройками

    $Selenium.Navigate().GoToUrl("https://google.com")
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::Id('APjFqb'))
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::XPath('//*[@id="APjFqb"]'))
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::Name('q'))
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::XPath('//*[@name="q"]'))
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::ClassName('gLFyf'))
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::CssSelector('[jsname="yZiJbe"]'))
    $Search = $Selenium.FindElements([OpenQA.Selenium.By]::TagName('textarea')) | Where-Object ComputedAccessibleRole -eq combobox
    $Search.SendKeys("calculator online")
    $Search.SendKeys([OpenQA.Selenium.Keys]::Enter)

    Start-Sleep 1
    $div = $Selenium.FindElements([OpenQA.Selenium.By]::TagName("div"))
    $2 = $div | Where-Object {($_.ComputedAccessibleRole -eq "button") -and ($_.ComputedAccessibleLabel -eq "2")}
    $2.Click()
    $2.Click()
    $plus = $div | Where-Object {($_.ComputedAccessibleRole -eq "button") -and ($_.Text -eq "+")}
    $plus.Click()
    $3 = $Selenium.FindElement([OpenQA.Selenium.By]::CssSelector('[jsname="KN1kY"]'))
    $3.Click()
    $3.Click()
    $sum = $Selenium.FindElement([OpenQA.Selenium.By]::CssSelector('[jsname="Pt8tGc"]'))
    $sum.Click()
    $result = $Selenium.FindElement([OpenQA.Selenium.By]::CssSelector('[jsname="VssY5c"]')).Text
    Write-Host "Result: $result" -ForegroundColor Green
}
finally {
    $Selenium.Close()
    $Selenium.Quit()
}

Search for calculator online in the search string, execute 22+33 using the clicks and output the result to the console:

PS C:\Users\lifailon> . 'C:\Users\lifailon\Documents\Git\Deploy-Selenium\Selenium-Example.ps1'
Result: 55

Selenium-Modules

Install module PS.Selenium.Modules:

PS > Install-Module PS.Selenium.Modules
PS > Get-Command -Module PS.Selenium.Modules

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Get-LangChain                                      0.1        PS.Selenium.Modules
Function        Get-Phind                                          0.1        PS.Selenium.Modules
Function        Get-SpeedTest                                      0.1        PS.Selenium.Modules
Function        Get-Translation                                    0.1        PS.Selenium.Modules
Function        Get-YaGPT                                          0.1        PS.Selenium.Modules

ChatGPT

⚠️ In the example, the server ChatGPT no longer works. A new repository GPT-to-Code created to work with different AI models.

🐥 The idea is that if you can't get an API key, you can use a third-party 🙏 free Chat-GPT web interface that doesn't require authorization to be able to implement the interface for your scripts or just chat with the bot in the PowerShell console.

🚀 Install module Get-GPT

To install the module in the default PowerShell modules directory, run the command in your console:

Invoke-RestMethod https://raw.githubusercontent.com/Lifailon/Selenium-Modules/rsa/Modules/Get-GPT/Get-GPT.psm1 | Out-File -FilePath "$(New-Item -Path "$($($Env:PSModulePath -split ";")[0])\Get-GPT" -ItemType Directory -Force)\Get-GPT.psm1" -Force

🎉 Example Get-GPT

PS C:\Users\lifailon> Import-Module Get-GPT

PS C:\Users\lifailon> Get-GPT "Исполняй роль калькулятора. Посчитай сумму чисел: 22+33"
Конечно! Сумма чисел 22 и 33 равна 55. Чем еще я могу помочь?

PS C:\Users\lifailon> Get-GPT "Исполняй роль интерпретатора PowerShell. Выведи результат команды: Write-Host $(22+33)"
Конечно! Вот результат выполнения команды "Write-Host 55":
55

PS C:\Users\lifailon> Get-GPT "Исполняй роль переводчика. Переведи текст на русский язык: Hi! How can I help you?"
Привет! Как я могу тебе помочь?

PS C:\Users\lifailon> Get-GPT "Напиши код на языке PowerShell, который позволяет получить прогноз погоды"
Конечно! Вот пример кода на языке PowerShell, который использует API OpenWeatherMap для получения прогноза погоды:
# Установка модуля Invoke-RestMethod, если необходимо
if (-not (Get-Module -ListAvailable -Name 'PowerShellGet')) {
    Install-PackageProvider -Name 'NuGet' -Force
}
if (-not (Get-Module -ListAvailable -Name 'PackageManagement')) {
    Install-Module -Name 'PackageManagement' -Force
}
if (-not (Get-Module -ListAvailable -Name 'PowerShellGet')) {
    Install-Module -Name 'PowerShellGet' -Force
}
if (-not (Get-Module -ListAvailable -Name 'Invoke-RestMethod')) {
    Install-Module -Name 'Invoke-RestMethod' -Force
}

# Замените 'YOUR_API_KEY' на ваш ключ API OpenWeatherMap
$apiKey = 'YOUR_API_KEY'

# Замените 'CITY_NAME' на название города, для которого нужен прогноз погоды
$city = 'CITY_NAME'

# Формирование URL-запроса к API OpenWeatherMap
$url = "http://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey"

# Получение данных о погоде через API
$response = Invoke-RestMethod -Uri $url

# Извлечение нужной информации из ответа API
$temperature = $response.main.temp
$description = $response.weather[0].description

# Вывод информации о погоде
Write-Host "Текущая температура в городе $city: $temperature градусов Цельсия"
Write-Host "Описание погоды: $description"
Не забудьте заменить 'YOUR_API_KEY' на ваш собственный ключ API OpenWeatherMap и 'CITY_NAME' на название города, для которого вы хотите получить прогноз погоды. После запуска скрипта, вы увидите текущую температуру и описание погоды

Text Translation

Translation text directly in the PowerShell console.

The module uses 2 providers to choose from:

🚀 Install module Get-Translation

Invoke-RestMethod https://raw.githubusercontent.com/Lifailon/Selenium-Modules/rsa/Modules/Get-Translation/Get-Translation.psm1 | Out-File -FilePath "$(New-Item -Path "$($($Env:PSModulePath -split ";")[0])\Get-Translation" -ItemType Directory -Force)\Get-Translation.psm1" -Force

🎉 Example Get-Translation

PS C:\Users\lifailon> Get-Translation -Provider DeepL -Text "I translating the text"
Я перевожу текст

PS C:\Users\lifailon> Get-Translation -Provider DeepL -Text "Я перевожу текст"
I'm translating the text

PS C:\Users\lifailon> Get-Translation -Provider Google -Text "I translating the text"
Я переводил текст

PS C:\Users\lifailon> Get-Translation -Provider Google -Text "Я перевожу текст" -Language en
I am translating the text

Console-Translate

You can use the Console-Trsanslate module to free translate text without dependencies using the API (Google public key and DeepLX free API):

Invoke-Expression(New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/Lifailon/Console-Translate/rsa/Deploy-Console-Translate.ps1")

Internet SpeedTest

The module uses 3 providers to choose from:

📊 The module is debugged on PowerShell Core and can be used to collect metrics with output to InfluxDB. As an example, you can use other work Ookla-SpeedTest-API, which alternatively uses InternetExplorer via COM Interface.

🚀 Install module Get-SpeedTest

Invoke-RestMethod https://raw.githubusercontent.com/Lifailon/Selenium-Modules/rsa/Modules/Get-SpeedTest/Get-SpeedTest.psm1 | Out-File -FilePath "$(New-Item -Path "$($($Env:PSModulePath -split ";")[0])\Get-SpeedTest" -ItemType Directory -Force)\Get-SpeedTest.psm1" -Force

🎉 Example Get-SpeedTest

PS C:\Users\lifailon\Desktop> Get-SpeedTest -Provider Libre

Download Upload    Ping    Jitter
-------- ------    ----    ------
171 Mbps 28.0 Mbps 22.0 ms 1.40 ms

PS C:\Users\lifailon\Desktop> Get-SpeedTest -Provider Open 

Download : 254.68 Mbps
Upload   : 80.24 Mbps
Ping     : 5.6 ms
Jitter   : 0.30 ms
Carrier  : SEVEN-SKY
Server   : Stockholm
Result   : openspeedtest.com/results/63074923
Date     : Jan 9 2024 4:06 PM UTC

PS C:\Users\lifailon\Desktop> Get-SpeedTest -Provider Ookla

date               : 09.01.2024 19:08:23
id                 : 15729550610
connection_icon    : wireless
download           : 272707
upload             : 272986
latency            : 3
distance           : 0
country_code       : RU
server_id          : 53268
server_name        : Moscow
sponsor_name       : City-Telecom ZAO
sponsor_url        :
connection_mode    : multi
isp_name           : Seven Sky
isp_rating         : 3.5
test_rank          : 100
test_grade         : A+
test_rating        : 5
idle_latency       : 4
download_latency   : 50
upload_latency     : 14
additional_servers : {@{server_id=22121; server_name=Moscow; sponsor_name=MosLine Group LLC}, @{server_id=23499; server_name=Moscow; sponsor_name=Марьино.net},
                      @{server_id=11266; server_name=Moscow; sponsor_name=INETCOM LLC}}
path               : result/15729550610
hasSecondary       : True
There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.1.1 148 2/5/2024
0.1.0 130 2/5/2024