与powershell的第二个浏览器选项卡进行交互

问题描述 投票:1回答:1

我写了一个powershell脚本来自动登录我的网站。它工作正常。我想扩展脚本以在新选项卡中打开另一个站点并自动登录。我能够在没有问题的情况下打开第二个选项卡但是传递凭据的代码在第一个选项卡中运行而不是第二个标签。为了验证这一点,我快速点击第一个选项卡上的后退按钮,在第二个选项卡打开并观看之前返回到登录屏幕,即使第二个选项卡是前面的选项卡,脚本也尝试登录到首先打开标签。如何确保脚本代码与下一个打开的选项卡交互,而不是与打开的第一个选项卡交互。我在下面使用的完整代码。谢谢参观。

 #Create an IE object
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible = $true

#Open the site
$ie.Navigate("www.mysite.com")

#Pauses the script to wait for the site to load
while($ie.Busy -eq $true){Start-Sleep -seconds 3;}

#Feeds the credentials to the form 
#Note: you will need to view the source code of your site to get the correct element IDs
$usernamefield = $ie.Document.getElementByID('username')
$usernamefield.value = 'myuser'
$passwordfield = $ie.Document.getElementByID('password')
$passwordfield.value = 'mypassword'
while($ie.Busy -eq $true){Start-Sleep -seconds 2;}
$submitButton = $ie.document.getElementByID('loginbutton').click()
#######################################################################################################
while($ie.Busy -eq $true){Start-Sleep -seconds 5;}
#Open site 2
$ie.Navigate2("www.myothersite.com", 2048)
$ie.Visible = $true
#Pauses the script to wait for the site to load
while($ie.Busy -eq $true){Start-Sleep -seconds 3;}

#Feeds the credentials to the form 
#Note: you will need to view the source code of your site to get the correct element IDs
$usernamefield = $ie.Document.getElementByID('username')
$usernamefield.value = 'myuser'
$passwordfield = $ie.Document.getElementByID('password')
$passwordfield.value = 'mypassword'
while($ie.Busy -eq $true){Start-Sleep -seconds 2;}
$submitButton = $ie.document.getElementByID('loginbutton').click()
powershell
1个回答
0
投票

问题是IE不会为您打开的新webbrowser实例提供任何类型的句柄。是的,标签被认为是新的浏览器。因此,您必须使用window.shell来寻找新对象。

This discussion在其中有更多细节,以便在事后需要激活特定选项卡。

$ie = New-Object -ComObject 'internetExplorer.Application'

$ie.Navigate("https://example.com/")

$ie.Visible = $true

do { sleep 1 } until (-not $ie.Busy)

write-host "Working with tab " $ie.LocationUrl

### Open second tab

$SOUrl = "https://stackoverflow.com/"

$ie.Navigate($SOUrl, 0x800)
do { sleep 1 } until (-not $ie.Busy)

$win = (New-Object -comObject shell.Application)

do {
    $so_ie = (@($win.windows() | ? { $_.HWND -eq $ie.HWND -and $_.locationURL -eq $SOUrl })[0])
    sleep 1
} until ($so_ie)


write-host "Working with tab " $so_ie.LocationUrl
© www.soinside.com 2019 - 2024. All rights reserved.