【发布时间】:2020-01-21 19:39:48
【问题描述】:
我正在尝试更改从this site 拉出Team Statistics 表的代码中的多个标题名称 我不确定在我的代码中手动更改它们的位置。
例如,我尝试在添加“TEAM”标题的行中手动将标题 8、GF 更改为 GFPG,但出现错误:
使用“2”参数调用“添加”的异常:“项目已添加。字典中的键:'GF' 正在添加的键:'GF'” 在 C:\NHLScraper.ps1:32 字符:5 + $objHash.Add($headers[$j],$rowdata[$j])
我的代码:
$url = "https://www.hockey-reference.com/leagues/NHL_2020.html"
#getting the data
$data = Invoke-WebRequest $url
#grab the third table
$table = $data.ParsedHtml.getElementsByTagName("table") | Select -skip 2 | Select -First 1
#get the rows of the Team Statistics table
$rows = $table.rows
#get table headers
$headers = $rows.item(1).children | select -ExpandProperty InnerText
#count the number of rows
$NumOfRows = $rows | Measure-Object
#Manually injecting TEAM header
$headers = @($headers[0];'TEAM';$headers[1..($headers.Length-1)])
#enumerate the remaining rows (we need to skip the header row) and create a custom object
$out = for ($i=2;$i -lt $NumofRows.Count;$i++) {
#define an empty hashtable
$objHash=[ordered]@{}
#getting the child rows
$rowdata = $rows.item($i).children | select -ExpandProperty InnerText
for ($j=0;$j -lt $headers.count;$j++) {
#add each row of data to the hash table using the correlated table header value
$objHash.Add($headers[$j],$rowdata[$j])
}
#turn the hashtable into a custom object
[pscustomobject]$objHash
}
$out | Select TEAM,AvAge,GP,W,L,OL,PTS,PTS%,GF,GA,SOW,SOL,SRS,SOS,TG/G,EVGF,EVGA,PP,PPO,PP%,PPA,PPOA,PK%,SH,SHA,PIM/G,oPIM/G,S,S%,SA,SV%,SO -SkipLast 1 | Export-Csv -Path "C:\$((Get-Date).ToString("'NHL Stats' yyyy-MM-dd")).csv" -NoTypeInformation
【问题讨论】:
-
我刚刚运行了你的代码几次,第 9 个元素是 GFPG 并且没有错误。你确定你得到那个错误吗?是否有可能在每次循环时都没有创建新的哈希表?
-
你在哪里改的?在我实施了你的解决方案之后,我仍然不知道在哪里将 GF 更改为 GFPG
标签: windows powershell web-scraping html-parsing powershell-4.0