如何正确访问Internet Explorer的元素?

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

我有一个脚本,可以测试我们的某个网站是否正常运行。

  1. 测试1:它检查HTTP状态。 (这里没问题)
  2. 测试2:它检查用户授权是否正常,因为我们过去曾遇到过这方面的问题。

然后等待一个小时再次运行两个测试。

脚本的整体结构如下(伪代码):

while (1 -eq 1) {
    test1
    if ($result -eq "pass") {
        test2
    }
    start-sleep -seconds 3600
}

测试2是问题发生的地方。此测试的工作原理是:导航到登录页面,输入凭据,单击登录按钮。检查URL,因为成功登录会导致与登录页面不同的URL。这工作正常,除了(看似随机)循环,它无法访问页面的元素:用户名和密码字段和登录按钮。抛出的异常取决于我如何更改代码以尝试解决问题。

我收到的一些错误消息包括:

System.Runtime.InteropServices.COMException RPC服务器不可用。 (HRESULT异常:0x800706BA)

System.Runtime.InteropServices.COMException在此对象上找不到属性“value”。验证该属性是否存在且可以设置。

System.Runtime.InteropServices.COMException OperationStopped:(:) [],COMException HResult:-2147352319不支持此类接口

System.Runtime.InteropServices.COMException OperationStopped:(:) [],COMException HResult:-2147352319不支持此命令。

违规代码是尝试使用getElementByID访问页面元素的任何内容,例如:

$ie.Document.getElementByID("username").value = $userame

同样,奇怪的是代码运行好几个小时......但是,通常在半夜,它随机变得无法访问页面元素。

以下是测试2的完整代码,以防有助于:

$ie = New-Object -ComObject "internetExplorer.Application"
#$ie.Visible = $true
$ie.navigate2($loginPage)
while ($ie.busy -eq $true) {start-sleep -seconds 1}
$ie.Document.getElementByID("username").value = $username
$ie.Document.getElementByID("password").value = $password
$ie.Document.getElementByID("login-button").click()
while ($ie.busy -eq $true) {start-sleep -seconds 1}
if ($ie.Document.url -eq $landingPage) {
    #success
} else {
    #failure
}
$ie.quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($ie) | out-null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
$process = get-process -name "iexplore"
while ($process) {
    try {
        stop-process -name "iexplore" -ea stop
    } catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
        #do nothing
    }
    try {
        $process = get-process -name "iexplore" -ea stop
    } catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
        $process = $null
    }
}
powershell dom com internet-explorer-11
1个回答
0
投票

直到我能弄清楚问题是什么,我已经实施了一个解决方法。我将有问题的代码放在try块中。在catch块中,我重新启动脚本。以下不完全是我的脚本中的实现方式,但它给你的想法:

try {
    $ie.Document.getElementByID("username").value = $username
} catch {
    start powershell {$scriptPath}
    exit
}

当脚本重新启动时,可以使用getElementByID再次访问页面的元素。

© www.soinside.com 2019 - 2024. All rights reserved.