Récupérer tous les fonds d'écran Bing en PowerShell
Bonjour à tous,
Avancant de plus en plus dans le monde du scripting PowerShell, on n'apprend jamais mieux qu'en faisant soit-même.
Chaque jour, Bing propose un nouveau fond d'écran, fond que je trouve sympatique chaque jour et dont certains j'aimerai les garder pour plus tard.
Je me suis mis à chercher des sites répertoriant les images de Bing et j'en ai trouvé un qui contient tout l'historique des images proposées :
Mais le plus intéressant est de récupérer les images, et le dossier où se trouve les images est ici : http://www.istartedsomething.com/bingimages/cache/
A partir de là, on peut partir sur nos claviers et commencer à récupérer les liens puis les images, et le tout en PowerShell :)
Le script récupère la liste de tous les liens de chaque image caractérisés par la balise HTML "a".
Ensuite il génère l'arborescence fonction de la zone géographique de chaque image.
Sil'image existe déjà, il passe à la suivante et n'écrase pas l'existante (fais gagner beaucoup de temps).
Aperçu du résultat :
Le script et le dossier créé | ![]() |
Le contenu du dossier créé | ![]() |
La traille du dossier après récupération des images | ![]() |
Le script PowerShell :
begin {
$bing_src_wallpapers_url = "http://www.istartedsomething.com/bingimages/cache/"
$repository = "$(Get-Location)\Bing Wallpapers"
function Get-MarkupTag {
#.Synopsis
# Extracts out a markup language (HTML or XML) tag from within a document
#.Description
# Extracts out a markup language (HTML or XML) tag from within a document.
# Returns the tag, the text within the tag, and, if possible, the tag converted
# to XML
#.Parameter tag
# The tag to extract, e.g. "a", "div"
#.Parameter html
# The text to extract the tag from
#.Example
# # Download the Microsoft front page and extract out links and div tags
# $microsoft = (New-Object Net.Webclient).DownloadString("http://www.microsoft.com/")
# "a", "div" | Get-MarkupTag -html $microsoft
#.Example
# # Extract the rows from ConvertTo-HTML
# $text = Get-ChildItem | Select Name, LastWriteTime | ConvertTo-HTML | Out-String
# Get-MarkupTag "tr" $text
param(
[Parameter(ValueFromPipeline=$true,Position=0)]$tag,
[Parameter(Position=1)][string]$html)
begin {
$replacements = @{
"<BR>" = "<BR />"
"<HR>" = "<HR />"
" " = " "
'¯'='¯'
'Ð'='Ð'
'¶'='¶'
'¥'='¥'
'º'='º'
'¹'='¹'
'ª'='ª'
''=''
'²'='²'
'Ç'='Ç'
'Î'='Î'
'¤'='¤'
'½'='½'
'§'='§'
'Â'='â'
'Û'='Û'
'±'='±'
'®'='®'
'´'='´'
'Õ'='Õ'
'¦'='¦'
'£'='£'
'Í'='Í'
'·'='·'
'Ô'='Ô'
'¼'='¼'
'¨'='¨'
'Ó'='Ó'
'°'='°'
'Ý'='Ý'
'À'='À'
'Ö'='Ö'
'"'='"'
'Ã'='Ã'
'Þ'='Þ'
'¾'='¾'
'¿'='¿'
'×'='×'
'Ø'='Ø'
'÷'='÷'
'¡'='¡'
'³'='³'
'Ï'='Ï'
'¢'='¢'
'©'='©'
'Ä'='Ä'
'Ò'='Ò'
'Å'='Å'
'È'='È'
'Ü'='Ü'
'Á'='Á'
'Ì'='Ì'
'Ñ'='Ñ'
'Ê'='Ê'
'¸'='¸'
'Ù'='Ù'
'ß'='ß'
'»'='»'
'ë'='ë'
'É'='É'
'µ'='µ'
'¬'='¬'
'Ú'='Ú'
'Æ'='Æ'
'€'= "€"
}
}
process {
foreach ($r in $replacements.GetEnumerator()) {
$l = 0
do {
$l = $html.IndexOf($r.Key, $l, [StringComparison]"CurrentCultureIgnoreCase")
if ($l -ne -1) {
$html = $html.Remove($l, $r.Key.Length)
$html = $html.Insert($l, $r.Value)
}
} while ($l -ne -1)
}
$r = New-Object Text.RegularExpressions.Regex ('</' + $tag + '>'), ("Singleline", "IgnoreCase")
$endTags = @($r.Matches($html))
$r = New-Object Text.RegularExpressions.Regex ('<' + $tag + '[^>]*>'), ("Singleline", "IgnoreCase")
$startTags = @($r.Matches($html))
$tagText = @()
if ($startTags.Count -eq $endTags.Count) {
$allTags = $startTags + $endTags | Sort-Object Index
$startTags = New-Object Collections.Stack
foreach($t in $allTags) {
if (-not $t) { continue }
if ($t.Value -like "<$tag*") {
$startTags.Push($t)
} else {
$start = $startTags.Pop()
$tagText+=($html.Substring($start.Index, $t.Index + $t.Length - $start.Index))
}
}
} else {
# Unbalanced document, use start tags only and make sure that the tag is self-enclosed
$startTags | Foreach-Object {
$t = "$($_.Value)"
if ($t -notlike "*/>") {
$t = $t.Insert($t.Length - 1, "/")
}
$tagText+=$t
}
}
foreach ($t in $tagText) {
if (-not $t) {continue }
# Correct HTML which doesn't quote the attributes so it can be coerced into XML
$inTag = $false
for ($i = 0; $i -lt $t.Length; $i++) {
if ($t[$i] -eq "<") {
$inTag = $true
} else {
if ($t[$i] -eq ">") {
$inTag = $false
}
}
if ($inTag -and ($t[$i] -eq "=")) {
if ($t[$i + 1] -notmatch '[''|"]') {
$endQuoteSpot = $t.IndexOfAny(" >", $i + 1)
# Find the end of the attribute, then quote
$t = $t.Insert($i + 1, "'")
$t = $t.Insert($endQuoteSpot + 1, "'")
$i = $endQuoteSpot
} else {
# Make sure the quotes are correctly formatted, otherwise,
# end the quotes manually
$whichQuote = "$($Matches.Values)"
$endQuoteSpot = $t.IndexOf($whichQuote, $i + 2)
$i = $endQuoteSpot
}
}
}
$t | Select-Object @{
Name='Tag'
Expression={$_}
}, @{
Name='Xml'
Expression= {
([xml]$t).$tag
trap {
Write-Verbose ($_ | Out-String)
continue
}
}
}
}
}
}
function Download {
param($lang,$item)
Try{
if(!(Test-Path "$repository\$lang")) {
New-Item -ItemType directory -Path "$repository\$lang" | Out-Null
}
if(!(Test-Path ("$repository\$lang\$item"))) {
Write-Host "`t$repository\$lang\$item" -NoNewLine
(New-Object System.Net.WebClient).DownloadFile($bing_src_wallpapers_url+$item,"$repository\$lang\$item")
Write-Host -Foregroundcolor:Green " done"
}
}
Catch [Exception]{
Write-Warning "`nFail to download file from URL"
Write-Host -ForeGroundColor:red $error[0].Exception.Message
}
}
}
process {
$pics = Get-MarkupTag -tag "a" -html ((New-Object Net.Webclient).DownloadString($bing_src_wallpapers_url))
$fileName = $pics | where {$_ -match ".jpg"} |% {$_.tag.split('"')[1]}
Write-Host "Found $($fileName.count) Bing wallpapers" -ForegroundColor:Cyan
foreach($i in $fileName) {
if($i -match "DE-DE") {$lang = "DE-DE"}
elseif($i -match "EN-AU") {$lang = "EN-AU"}
elseif($i -match "EN-CA") {$lang = "EN-CA"}
elseif($i -match "EN-GB") {$lang = "EN-GB"}
elseif($i -match "EN-US") {$lang = "EN-US"}
elseif($i -match "FR-FR") {$lang = "FR-FR"}
elseif($i -match "JA-JP") {$lang = "JA-JP"}
elseif($i -match "ROW") {$lang = "ROW"}
elseif($i -match "ZH-CN") {$lang = "ZH-CN"}
else {$lang = "UNKNOW"}
Download -lang $lang -item $i
}
}
end {
Read-Host
}
Mots-clés: powershell,, bing,
Comments powered by CComment