Method “getElementsByClassName” not recognized

2019-02-19 23:24发布

问题:

I want to start Windows Explorer and login to a website. After logging in I want to click logout textlink. But I am getting this error:

Method invocation failed because [mshtml.HTMLDocumentClass] doesn't contain a
method named 'getElementsByClassName'
At C:\Users\ntando.ntuli\Desktop\test.ps1:29 char:43
+  $Link=$ie.Document.getElementsByClassName <<<< ("underline") | Where-Object {$_.ClassName -eq "underline"}
    + CategoryInfo          : InvalidOperation: (getElementsByClassName:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Here is the code I am using

$IE = New-Object -COM InternetExplorer.Application;
$IE.Visible = $true;
$IE.Navigate("http://192.168.2.73:6500/ouaf/loginPage.jsp");

# Wait a few seconds and then launch the executable.
while ($IE.Busy -eq $true) {
  Start-Sleep -Milliseconds 2000;
}

# The following UsernameElement, PasswordElement, and LoginElement need to be
# modified first.  See the notes at the top of the script for more details.

$elementMatchText = "You are logged in as English System"
$IE.Document.getElementById("userId").value = "username"
$IE.Document.getElementByID("password").value="password"
$IE.Document.getElementById("loginButton").Click()

while ($IE.Busy -eq $true) {
  Start-Sleep -Milliseconds 2000; 
} 

#Logout textlink classname
$Link = $ie.Document.getElementsByClassName("underline") |
        Where-Object {$_.ClassName -eq "underline"}
$Link.Click()

回答1:

It seems that you can only call getElementsByClassName on the documentElement property of the Document:

$ie.Document.documentElement.getElementsByClassName("underline")


回答2:

I've seen getElementsByClassName() fail before, even though it should work, according to the documentation. As a workaround select your elements by tag name (you seem to be looking for <a> tags), then filter for the ClassName attribute. I'd also restrict the results to the first occurrence in case more than one matching element is found:

$Link = $ie.Document.getElementsByTagName('a') |
        Where-Object { $_.ClassName -eq 'underline' } |
        Select-Object -First 1