Powershell with Selenium 4.x: Chrome options - powershell

I am able to successfully execute a Powershell script with Selenium 4.x although i need to run chrome under a user profile (which will persist). The objective is to save the cookies. For that I believe I will need to add options as defined in Saving chrome cookies Selenium. I do see something similar here although I need it for Powershell.
So how do I implement options that can be used by this command. (This command is primarily for selenium 4.x).
$browser = Start-SeDriver -Browser Chrome
This is all I could get, but I am unsure how to add it all up:
$ChromeOptions.addArguments("c:/users/PsUser");

With Module https://github.com/adamdriscoll/selenium-powershell v4:
$browser = Start-SeDriver -Browser Chrome -Arguments "--user-data-dir=C:\Users\$($env:username)\AppData\Local\Google\Chrome\User Data"
Without Module:
When you instantiate the ChromeDriver object you can pass a ChromeOptions argument.
So basically:
# Your working directory
$workingPath = 'C:\selenium'
# Add the working directory to the environment path.
# This is required for the ChromeDriver to work.
if (($env:Path -split ';') -notcontains $workingPath) {
$env:Path += ";$workingPath"
}
# OPTION 1: Import Selenium to PowerShell using the Add-Type cmdlet.
Add-Type -Path "$($workingPath)\WebDriver.dll"
# Create a new ChromeDriver Object instance.
$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.AddArgument("--user-data-dir=C:\Users\$($env:username)\AppData\Local\Google\Chrome\User Data")
$chrome = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
# Launch a browser and go to URL
$ChromeDriver.Navigate().GoToURL('https://google.com')
# Cleanup
$ChromeDriver.Close()
$ChromeDriver.Quit()

Related

Selenium ChromeDriver displays SessionNotCreated after launching Chrome and then exiting

I'm attempting to create a PowerShell script to automate some testing tasks but falling at the first hurdle.
I have a folder with ChromeDriver 105.0.5195.52 (chromedriver.exe) and the Selenium Web Driver 4.4.0 for .NET (WebDriver.dll).
On the test server, .NET version 4.8.03761 and Google Chrome 105.0.5195.102 (64-Bit) are installed.
After executing the script, Chrome is briefly launched and then exits. I see the following message in the PowerShell window:
New-Object : Exception calling ".ctor" with "1" argument(s): "session not created
from tab crashed
(Session info: chrome=105.0.5195.102) (SessionNotCreated)"
In Task Manager, the ChromeDriver.exe continues to run. Subsequent runs yield the same
behaviour and message.
The script is:
$workingPath = 'C:\Users\Me\Desktop\LaunchTest'
if (($env:Path -split ';') -notcontains $workingPath) {
$env:Path += ";$workingPath"
}
$env:Path -split ';'
Add-Type -Path "$($workingPath)\WebDriver.dll"
$ChromeOptions = [OpenQA.Selenium.Chrome.ChromeOptions]::new()
$ChromeOptions.AddArguments('start-maximized')
$ChromeDriver = New-Object -TypeName "OpenQA.Selenium.Chrome.ChromeDriver" -ArgumentList #($ChromeOptions)
$ChromeDriver.Navigate().GoToURL('<https://google.co.uk>')
Any thoughts will be appreciated.
I faced quite similar problem.
My solution:
uninstall chrome 64-bit and remove its reminder
install chrome 32-bit instead

How to start Chromium Edge selenium webdriver in application mode using powershell

I would like to start the Chromium Edge selenium webdriver in application mode using powershell.
This is how you do it from the powershell command line without the selenium webdriver:
& "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --app="https://stackoverflow.com"
This is what I've tried so far but it doesn't seem to work.
Specifically, the Chromium Edge webdriver window starts up, but not in application mode.
$optionSettings = #{
BrowserName = ''
BinaryLocation = $pathToDriver
}
$options = New-Object -TypeName OpenQA.Selenium.Chrome.ChromeOptions -Property $optionSettings
$options.addArgument("app='https://stackoverflow.com'")
$service = [OpenQA.Selenium.Chrome.ChromeDriverService]::CreateDefaultService($pathToDriver, 'msedgedriver.exe')
$driver = New-Object -TypeName OpenQA.Selenium.Chrome.ChromeDriver -ArgumentList $service,$options
I've also tried substituting the following for the addArgument:
$options.addArgument("app=https://stackoverflow.com")
$options.addArgument("--app='https://stackoverflow.com'")
$options.addArgument("--app=https://stackoverflow.com")
Any ideas?
First, if you need to start Chromium Edge via Webdriver, you need to use EdgeDriver instead of ChromeDriver. Secondly, you need to use Selenium 4 webdriver or above.
Here is a simple demo, and it works well:
[System.Reflection.Assembly]::LoadFrom("E:\Selenium\WebDriver.dll")
$options = New-Object OpenQA.Selenium.Edge.EdgeOptions
$options.addArguments("--app=https://stackoverflow.com")
#$options.AcceptInsecureCertificates = $True
$driver = New-Object OpenQA.Selenium.Edge.EdgeDriver("C:\Users\Administrator\Desktop\",$options)
#$driver.Url = "https://stackoverflow.com"
Note: Modify the path parameters according to your own situation.

Open User Profile In Chrome using PowerShell and Selenium

So I have found little to no info on this topic, basically I'm just trying to use selenium to open up a chrome profile so that the settings are saved to be used in each run of the script. Please help as I am new to coding and have never used PowerShell.
So far the only semi successful attempt with no errors is as follows but still does not work..
$WebDriverPath = Resolve-Path "C:\selenium\WebDriver.dll"
Unblock-File $WebDriverPath
Add-Type -Path $WebDriverPath
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$CD = $ChromeDriver.AddArgument("--user-data-dir=C:\Users\jshaw\AppData\Local\Google\Chrome\User Data\Profile 2")
$CD = New-Object OpenQA.Selenium.Chrome.ChromeDriver
$CD.Navigate().GoToURL('https://www.google.com')
So i figured out how to do this! This loads your default profile; however, there is an issue when you do this. If you have Chrome open already it throws an error. when Chrome is closed all good! Now I know why people use customized profiles.
$ChromeOptions.AddArgument(
"--user-data-dir=C:\Users\TweakAir\AppData\Local\Google\Chrome\User Data"
)
$ChromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($ChromeOptions)
$ChromeDriver.Navigate().GoToURL($YourURL)```

How do you define firefox exe path in selenium with Powershell?

I'm trying to use selenium Firefox with powershell and I need to specify the firefox's executable (portable firefox). I can make my script work with chrome and I have found how to specify chrome's path but I had no luck with Firefox.
Here's all I got so far:
# Website and credential variables
$YourURL = "http://192.168.0.1/" # Website we'll access
# Invoke Selenium into our script!
# Geckodriver.exe
$env:PATH += ";D:\Powershell\webdriver"
Add-Type -Path "D:\Powershell\webdriver\WebDriver.dll"
Add-Type -Path "D:\Powershell\webdriver\WebDriver.Support.dll"
$ff_object = New-Object "OpenQA.Selenium.Firefox.FirefoxDriver"
Thanks a lot JimEvans! Here is my powershell working code:
$YourURL = "http://192.168.0.1/" # Website we'll access
$env:PATH += "C:\Users\Carl\Desktop\webdriver\" # Adds the path for ChromeDriver.exe to the environmental variable
Add-Type -Path "C:\Users\Carl\Desktop\webdriver\WebDriver.dll" # Adding Selenium's .NET assembly (dll) to access it's classes in this PowerShell session
$FirefoxOptions = New-Object OpenQA.Selenium.Firefox.FirefoxOptions
$FirefoxOptions.BrowserExecutableLocation = "D:\PortableApps\FirefoxPortable\App\Firefox64\firefox.exe"
$FirefoxDriver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver($FirefoxOptions)
# Make use of Selenium's class methods to manage our browser at will
$FirefoxDriver.Navigate().GoToUrl($YourURL) # Browse to the specified website

Download file from website using SendKeys in Powershell

I'm trying to download an file from a particular website by clicking on the file icon. Website login works but i'm hoping to use keystroke "TAB" to navigate to the excel file and finally key "Enter" to download. Ran the code but resulted in the Powershell text of "FALSE". Any advice is appreciated! Thanks.
Reference: Table screenshot
$url = "https://abcdefg.com"
$username="test#gmail.com"
$password="TestPW"
$ie = New-Object -com internetexplorer.application;
$ie.visible = $true;
$ie.navigate($url);
while ($ie.Busy -eq $true)
{
Start-Sleep -Milliseconds 1000;
}
$ie.Document.getElementById("txtEmail").value = $username
$ie.Document.getElementByID("txtPassword").value=$password
$ie.Document.getElementById("Login").Click();
Start-Sleep -Milliseconds 10000
$obj = new-object -com WScript.Shell
$obj.AppActivate('Internet Explorer')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{Enter}')
Why are you doing that vs using web scraping to find the link you are trying to hit, and use the link URL directly?
Your post is really a duplicate of this Q&A.
Use PowerShell to automate website login and file download
SendKeys could work, but they are very hinky and on different systems may not function as you'd expect. There are better tools dedicated to do this, AutoIT, Selenium, WASP
--- That WASP tool still works, but has not been updated in a long while.
Using PowerShell 2.0 With Selenium to Automate Internet Explorer, Firefox, and Chrome
Internet Explorer
Next you want to obtain the Internet Explorer driver from this site. I
recommend version 2.41 because “as of 15 April 2014, IE 6 is no longer
supported”. This must reside in your current PATH so in your script
you may want to modify your PATH to ensure the executable
(IEDriverServer.exe) can be found there. If you’re wondering whether
to get the 32-bit or the 64-bit version, start with the 32-bit even if
you’ve got a 64-bit Windows.
At this point you’ll want to quickly instantiate Internet Explorer and
navigate somewhere. Great. Let’s do it.
# Load the Selenium .Net library
Add-Type -Path "C:\selenium\WebDriver.dll" # put your DLL on a local hard drive!
# Set the PATH to ensure IEDriverServer.exe can found
$env:PATH += ";N:\selenium"
# Instantiate Internet Explorer
$ie_object = New-Object "OpenQA.Selenium.IE.InternetExplorerDriver"
# Great! Now we have an Internet Explorer window appear. We can navigate to a new URL:
$ie_object.Navigate().GoToURL( "http://www.bbc.co.uk/languages" )
# This worked! The call won’t return until the page download is complete.
# Next let’s click on a link from the link text:
$link = $ie_object.FindElementByLinkText( "Spanish" )
$link.Click()
# display current URL
$ie_object.Url
Selenium Tutorial: All You Need To Know About Selenium WebDriver
Update for the OP
As for...
However the file does not have a redirected URL
Then you need to look deeper at the site, to find the anchor to the file that you can force click on.
Example:
# Scrape a web page with PowerShell
$w = Invoke-WebRequest -Uri 'https://www.reddit.com/r/PowerShell'
$w | Get-Member
$w.AllElements
$w.AllElements.Count
$w.Links.Count
$w.Links
$w.Forms
$w.Forms.Fields
$w.Forms[0]
$w.Forms[0].Fields
$w.RawContent
$w.ParsedHtml
once you find tag names, or the like, you need to parse that to get stuff out of it.
$w.AllElements | Where-Object -Property 'TagName' -EQ 'P' | Select-Object -Property 'InnerText'
For tables you have to dig more.
Extracting Tables from PowerShell’s Invoke-WebRequest