Skip to content

Instantly share code, notes, and snippets.

@lazywinadmin
Created February 16, 2018 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazywinadmin/b06e5e151c60207c2901ae7c64f97088 to your computer and use it in GitHub Desktop.
Save lazywinadmin/b06e5e151c60207c2901ae7c64f97088 to your computer and use it in GitHub Desktop.
Get Olympics 2018 medal ranking per country
function Get-HTMLTable
{
param (
[Parameter(Mandatory = $true)]
[Microsoft.PowerShell.Commands.HtmlWebResponseObject]$WebRequest,
[Parameter(Mandatory = $true)]
[int]$TableNumber
)
## Extract the tables out of the web request
$tables = @($WebRequest.ParsedHtml.getElementsByTagName("TABLE"))
$table = $tables[$TableNumber]
$titles = @()
$rows = @($table.Rows)
## Go through all of the rows in the table
foreach ($row in $rows)
{
$cells = @($row.Cells)
## If we've found a table header, remember its titles
if ($cells[0].tagName -eq "TH")
{
$titles = @($cells | % { ("" + $_.InnerText).Trim() })
continue
}
## If we haven't found any table headers, make up names "P1", "P2", etc.
if (-not $titles)
{
$titles = @(1 .. ($cells.Count + 2) | % { "P$_" })
}
## Now go through the cells in the the row. For each, try to find the
## title that represents that column and create a hashtable mapping those
## titles to content
$resultObject = [Ordered] @{ }
for ($counter = 0; $counter -lt $cells.Count; $counter++)
{
$title = $titles[$counter]
if (-not $title) { continue }
$resultObject[$title] = ("" + $cells[$counter].InnerText).Trim()
}
## And finally cast that hashtable to a PSCustomObject
[PSCustomObject]$resultObject
}
}
$w = invoke-webrequest http://www.bbc.co.uk/sport/winter-olympics/medals/countries
Get-HTMLTable -WebRequest $w -TableNumber 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment