Mar*_*ean 3 regex powershell powershell-3.0
我有以下网站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]
Run Code Online (Sandbox Code Playgroud)
数据图表位置
数据轨道标题
数据跟踪艺术家
列出的每首歌曲都有3个值(上图)与每个歌曲相关联,我想根据不同的图表位置(数字)捕捉每首歌曲的艺术家和标题.所以正则表达式找到实际的图表位置,然后是尾随的艺术家和标题.
如果我单独为艺术家和标题(下面的代码)运行RegEx,它会找到它们,但它只找到第一个艺术家和标题.我需要根据不同的图表位置找到每首歌曲的艺术家和标题.
$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
Run Code Online (Sandbox Code Playgroud)
使用正则表达式来解析部分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
}
Run Code Online (Sandbox Code Playgroud)
现在,让我们看看Tay-Tay如何做到:
PS C:\> $Top100 |Where-Object { $_.Artist -match "Taylor Swift" }
Position Title Artist
-------- ----- ------
42 Bad Blood Taylor Swift Feat. Kendrick Lamar
Run Code Online (Sandbox Code Playgroud)
甜!
| 归档时间: |
|
| 查看次数: |
239 次 |
| 最近记录: |