Damien Damien - 15 days ago 5
HTML Question

Parse a website and turn span tags into variables

How would I call a URL and turn the page elements into variables to use in PowerShell?

The HTML page looks like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<span class="server1var1">8</span>
<span class="server1var2">2</span>

<span class="server2var1">5</span>
<span class="server2var2">1</span>

</body>
</html>


Then in PowerShell I want these variables:

$server1var1 = "8"
$server1var2 = "2"

$server2var1 = "5"
$server2var2 = "1"


Accepting the answer below with one modification to make it work for me. Changing
$_.textContent
to
$_.innerhtml
solved the issue.

$content = Invoke-WebRequest -Uri 'http://gameadmin.zerosurvival.com/servercodes.php'
$content.ParsedHtml.getElementsByTagName('span') | ForEach-Object {
New-Variable -Name $_.className -Value $_.innerhtml
}

Answer

Use the Invoke-WebRequest cmdlet to retrieve the content of your website. Then use the getElementsByTagName of the ParsedHtml property to retrieve all span tags. Finally turn them into a variable using the New-Variable cmdlet:

$content = Invoke-WebRequest -Uri 'http://gameadmin.zerosurvival.com/servercodes.php'
$content.ParsedHtml.getElementsByTagName('span') | ForEach-Object { 
    New-Variable -Name $_.className -Value $_.textContent 
    }

After you run this, if you type $server1var1 you will get 8.