使用PowerShell自动执行网站登录和文件下载

时间:2016-08-10 12:31:56

标签: powershell download automation browser-automation

我想使用PowerShell自动登录网站并下载PDF文件。互联网上有大量示例显示如何执行此操作(使用Invoke-WebRequestWebClientHttpWebRequestInternetExplorer.Application),但大多数不需要首先登录。有些人通过登录显示它,但我无法让它们工作。我使用InternetExplorer.Application

结束了
$username = "xxxxx"
$password = "yyyyy"
$url = "https://example.com/login.aspx"
$usernameElementId = "aaaaa"
$passwordElementId = "bbbbb"
$submitButtonElementId = "ccccc"

$ie = New-Object -com InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate($url)

while($ie.ReadyState -ne 4 -or $ie.Busy) {Start-Sleep -m 100}

$ie.Document.getElementById($usernameControlId).value = $username
$ie.Document.getElementById($passwordControlId).value = $password
$ie.Document.getElementById($submitButtonElementId).click()

while($ie.ReadyState -ne 4 -or $ie.Busy) {Start-Sleep -m 100}
Start-Sleep -m 2000

$url = "https://example.com/statements/201607.pdf"
$outFilePath = "C:\Downloads\Statement_201607.pdf"
$ie.Navigate($url)

while($ie.ReadyState -ne 4 -or $ie.Busy) {Start-Sleep -m 100}

# Script works up to this point--the pdf document is shown in IE.
#The file downloaded in the next step is empty.

$ie.Document.body | Out-File -FilePath $outFilePath

我的问题:如何在脚本的最后一步中下载PDF文档?

我已经尝试使用WebClientInvoke-WebRequest执行相同的任务,但由于身份验证,我不断收到错误。我已经尝试在登录后捕获cookie并将其传递给下一个请求,但没有。如果某人有一个使用其他方式做这件事的工作示例,我全都耳朵。事实上,我倾向于尽可能避免自动化IE,但我会采取任何有效的解决方案。

1 个答案:

答案 0 :(得分:2)

理想情况下,您可以使用Invoke-WebRequest,但这实际上取决于网站的设置方式。如果它只是查询数据库的登录并从中生成一个cookie,那么很可能(但仍值得一试):

$url = "https://example.com/statements/201607.pdf"
$outFilePath = "C:\Downloads\Statement_201607.pdf"

# Prompt for password
Invoke-WebRequest -Uri $url -Credential MyUser -OutFile $outFilePath
# MyUser can be substituted with a credential object but it's complex, Google it

哎呀,根据它可能公开的网站(只是无法访问),尝试没有Credential参数。

根据网站的不同,他们可能会下载一些API,请您自行联系:

$proxy = New-WebServiceProxy -Uri "https://example.com/webservices.asmx" -Credential MyUser
# Again MyUser can be substituted with a credential object
$proxy.GetMyStatement("201607") | Out-File $outFilePath
# Name and syntax depend on how it is designed and may vary wildly from example

作为最后的手段......

#Wait for Download Dialog box to pop up
Sleep 5
while($ie.Busy){Sleep 1} 
#------------------------------
#Hit "S" on the keyboard to hit the "Save" button on the download box
$obj = new-object -com WScript.Shell
$obj.AppActivate('Internet Explorer')
$obj.SendKeys('s')

#Hit "Enter" to save the file
$obj.SendKeys('{Enter}')

#Closes IE Downloads window
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{Enter}')

请注意,您需要禁用任何浏览器内的PDF查看器,以便将其视为标准下载,在IE11中,这可能很棘手,因为它由PDF查看器管理。如果您使用的是Adobe Reader,则需要卸载BrowserIntegration功能。基本上当你手动点击它时,你想得到“运行或保存?”选项。