Error with GetElementsByClassName

I have created a function to get the definition/s of a word from a website, which goes as following:

function GetWordDefinition($Word, $Website, $ClassName)
    $Word = [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding(1251).GetBytes($Word));
    (Invoke-WebRequest ($Website+$Word)).ParsedHTML.GetElementsByClassName($ClassName)[0].InnerText;

The $Word parameter means the word to get the definitions of, $Website is the link for the website to get the definition of the word from, $ClassName is the name of the HTML class element in which will contain the definition/s of the word within the website, so, let’s suppose I want to get the definition of the word “Serendipity” from the website GetDefinition.Com (it’s just an example, I don’t know if such a website exists), and that the website returns the definition of words through GetDefinition.Com/[Word] (e.g GetDefinition dot Com/Sex, GetDefinition dot Com/Word, etc…), in a class named “Word Definition” then the program would invoke webrequest at GetDefinition dot Com/Serendipity, then it would get the ParsedHTML, then get the element with class name “Word Definition”, then get its InnerText. However, when I run the function, it appears an error like this (I’ve translated a part to English):

HRESULT exception: 0x800A01B6
At line:4 char:5
+     (Invoke-WebRequest ($Website+$Word)).ParsedHTML.GetElementsByClas ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], NotSupportedException
    + FullyQualifiedErrorId : System.NotSupportedException

The problem seems to be with GetElementsByClassName. Oddly, Yesterday this expression was working fine. Why is that happening and how can I address the issue?

My recommendation would be to step\walk through the code to understand where the error is coming from. Invoke the request in a variable, validate ParsedHTML contains what is expected, validate the class exists. If it just stopped working, it is possible that the website has changed its content\design.

1 Like

@Random-User @rob-simmers Well, this is strange. I’ve tested this function now and it is working well.

Just curios … the JavaScript function is case sensitive … so was the fix to lower case the G in get?

getElementsByClassName ??

If I’m not mistaken I didn’t alter the function, so it stayed with “Get” in upper case.