简体   繁体   中英

Automating Chrome WebDriver - Select Date from DatePicker using PowerShell and Selenium

Many thanks to:

for aspiring me to automate Chrome to perform a redundant task that I perform everyday.

I wish that I could select a date instead of sending keys to a datepicker using Selenium in PowerShell.

As per this weblink this is how they do it using Python. The task is very simple and PowerShell is bloat-free when it comes to dependencies.

Here is the story with all sorts of error which I am unable to solve:

$URL = "https://jqueryui.com/datepicker/"

[OpenQA.Selenium.Chrome.ChromeOptions]$ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$ChromeOptions.PageLoadStrategy = "eager"
$ChromeOptions.addArguments('start-maximized')
$ChromeDriver = New-Object -TypeName "OpenQA.Selenium.Chrome.ChromeDriver" -ArgumentList @($ChromeOptions)

$ChromeDriver.Navigate().GoToURL($URL)

$Frame = 0
$SelectFrame = $ChromeDriver.SwitchTo().Frame($Frame)

$SelectFrame.FindElementByXPath("//*[@id='datepicker']").click()

$SelectDate = "15"
$dateWidget = $ChromeDriver.FindElementById("ui-datepicker-div")
$cols = $dateWidget.FindElementByTagName("td")

foreach ($cells in $cols) {
    $date = $cells.getText() 
    if($date -eq $SelectDate) {
        $cells.FindElementByLinkTest($date).click()
        break
    }
}

Pause
Function Stop-ChromeDriver {Get-Process -Name chromedriver -ErrorAction SilentlyContinue | Stop-Process -ErrorAction SilentlyContinue}
$ChromeDriver.Close()
$ChromeDriver.Quit()
Stop-ChromeDriver

Would it be possible using PowerShell too?

Thank you for the blog mentions, I honestly don't know how I got across your question, but I did while googling something else. It's totally doable in PowerShell, try it like this after you've loaded Selenium's class.

$ChromeDriver.Navigate().gotourl('https://jqueryui.com/datepicker/')
# The following changes the frame, won't give an ugly error out if it fails:
try {$ChromeDriver.SwitchTo().Frame(0) | Out-Null} catch {} 
$ChromeDriver.FindElementsById('datepicker').click()
# For the following, [2] is the month you pick, [2] == March
$ChromeDriver.FindElementsByXPath("//div[@id='ui-datepicker-div']/div/a[2]/span").click() 
# For the following, "10" picks the day of the month, in this case, the 10th
$ChromeDriver.FindElementByLinkText("10").Click() 

Peace! - M6k

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM