我有以下网站http://www.shazam.com/charts/top-100/australia它显示歌曲,我想使用 RegEx 和 PowerShell 捕获歌曲。下面的 PowerShell 代码是我到目前为止所拥有的:
$ie = New-Object -comObject InternetExplorer.Application
$ie.navigate('http://www.shazam.com/charts/top-100/australia')
Start-Sleep -Seconds 10
$null = $ie.Document.body.innerhtml -match 'data-chart-position="1"(.|\n)*data-track-title=.*content="(.*)"><a href(.|\n)*data-track-artist=\W\W>(.|\n)*<meta\scontent="(.*)"\sitemprop';$shazam01artist = $matches[5];$shazam01title = $matches[2]
数据图表位置
数据轨道标题
数据跟踪艺术家
列出的每首歌曲都有与每首歌曲相关的 3 个值(上面),我想根据不同的图表位置(数字)捕获每首歌曲的艺术家和标题。因此,使用正则表达式来查找实际的图表位置,然后是尾随的艺术家和标题。
如果我单独为艺术家和标题(下面的代码)运行正则表达式,它会找到它们,但它只找到第一个艺术家和标题。我需要根据不同的图表位置找到每首歌曲的艺术家和标题。
$null = $ie.Document.body.innerhtml -match 'data-track-artist=\W\W>(.|\n)*<meta\scontent="(.*)"\sitemprop';$shazam01artist = $matches[2]
$null = $ie.Document.body.innerhtml -match 'data-track-title=.*content="(.*)"><a href';$shazam01title = $matches[1]
$shazam01artist
$shazam01title
最佳答案
使用正则表达式解析部分 HTML 绝对是一场噩梦,您可能需要重新考虑这种方法。
Invoke-WebRequest
返回一个名为 ParsedHtml
的属性,其中包含对预解析的 HTMLDocument 对象的引用。使用它来代替:
# Fetch the document
$Top100Response = Invoke-WebRequest -Uri 'http://www.shazam.com/charts/top-100/australia'
# Select all the "article" elements that contain charted tracks
$Top100Entries = $Top100Response.ParsedHtml.getElementsByTagName("article") |Where-Object {$_.className -eq 'ti__container'}
# Iterate over each article
$Top100 = foreach($Entry in $Top100Entries){
$Properties = @{
# Collect the chart position from the article element
Position = $Entry.getAttribute('data-chart-position',0)
}
# Iterate over the inner paragraphs containing the remaining details
$Entry.getElementsByTagName('p') |ForEach-Object {
if($_.className -eq 'ti__artist') {
# the ti__artist paragraph contains a META element that holds the artist name
$Properties['Artist'] = $_.getElementsByTagName('META').item(0).getAttribute('content',0)
} elseif ($_.className -eq 'ti__title') {
# the ti__title paragraph stores the title name directly in the content attribute
$Properties['Title'] = $_.getAttribute('content',0)
}
}
# Create a psobject based on the details we just collected
New-Object -TypeName psobject -Property $Properties
}
现在,让我们看看 Tay-Tay 在下面的表现如何:
PS C:\> $Top100 |Where-Object { $_.Artist -match "Taylor Swift" }
Position Title Artist
-------- ----- ------
42 Bad Blood Taylor Swift Feat. Kendrick Lamar
甜甜的!
关于RegEx PowerShell 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643227/