从Powershell与第二个浏览器选项卡进行交互

时间:2018-12-12 18:46:32

标签: powershell

我编写了一个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()

1 个答案:

答案 0 :(得分:0)

问题是IE无法为您打开的新Web浏览器实例提供任何处理。是的,标签被认为是新的浏览器。因此,您必须使用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