如何使用POWERSHELL下載必應每日圖片
今天想聊聊POWERSHELL對於WEB頁面的一些應用,本人也是最近才發覺其實PS也是可以做爬蟲的。。。所以想拋磚引玉給大家一個思路。
這次要用到的主要命令是 invoke-webrequest
先來看看官方對於這個命令的介紹
The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML elements.
https://docs.microsoft.com/zh-cn/powershell/module/Microsoft.PowerShell.Utility/Invoke-WebRequest?view=powershell-5.1
其實很好理解,這條PS命令可以讓你模擬瀏覽器發送請求給網站,並且得到你要的信息。
所以今天我們就從簡單的入手,用POWERSHELL下載每日必應的美圖
#bing每日圖片 完整代碼
$picurl = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=10"
$data = invoke-webrequest $picurl
$decode = convertfrom-json -inputobject $data.content
$images = $decode.images
foreach ($image in $images)
{
$imageurl = $image.url
$fullurl = "http://www.bing.com" + $imageurl
$name = $image.hsh
invoke-webrequest $fullurl -outfile ($name + ".jgp")
}
其中最關鍵的點是如何將亂碼一樣的content轉換為Json, 這裏要用到 convertfrom-json,由於powershell 是無法從下圖中得到的網頁代碼讀取任何有用信息所以必須要轉換。
在成功轉換之後存儲在$decode裏的變量變成PS易懂的格式,其中包含了該圖片的URL和名稱以及哪位大神的作品等等信息。再接下去就很好處理了。
foreach ($image in $images)
{
$imageurl = $image.url
#獲取圖片URL
$fullurl = "http://www.bing.com" + $imageurl
#補全URL
$name = $image.hsh
#獲取圖片名稱
invoke-webrequest $fullurl -outfile ($name + ".jgp")
#下載到PS運行目錄
}
腳本雖然簡單但是給我的啟發很大,讓我看到了PS的無限可能。
END
如何使用POWERSHELL下載必應每日圖片