Powershell 獲取特定的網(wǎng)頁信息的代碼
Powershell可以很輕松的獲取網(wǎng)頁的信息并讀取到對(duì)應(yīng)的內(nèi)容。如果對(duì)象的格式是XML或者Json,那就更容易處理了,一般經(jīng)常使用invoke-restmethod和invoke-webrequest這兩個(gè)命令。前者主要是獲取Json格式的內(nèi)容,后者可以獲取整個(gè)網(wǎng)頁的內(nèi)容。
比如說我希望查詢明天悉尼的天氣如何。網(wǎng)上隨便搜了一個(gè)提供API的站點(diǎn)
http://openweathermap.org/current#name
我打算搜索悉尼的,那么對(duì)應(yīng)的格式是
http://api.openweathermap.org/data/2.5/weather?q=sydney,au他會(huì)自動(dòng)生成一個(gè)Json格式的結(jié)果。

我們可以用invoke-restmethod直接獲取這個(gè)結(jié)果,比如說
$b=invoke-restmethod "http://api.openweathermap.org/data/2.5/weather?q=sydney,au"
$c=[pscustomobject]@{
'Description'=$b.weather.description
'name'=$b.name
'windspeed'=$b.wind.speed
}

我也可以直接使用invoke-webrequest抓取整個(gè)網(wǎng)頁的內(nèi)容,然后從Json的格式轉(zhuǎn)換過來也是一樣的
$a= Invoke-WebRequest -Uri "http://api.openweathermap.org/data/2.5/weather?q=sydney,au"$b=$a.Content | ConvertFrom-Json
類似的,如果我想獲取一個(gè)博客的RSS的最新內(nèi)容。可以使用invoke-webrequest抓取對(duì)應(yīng)的XML文件,比如
[xml]$a= Invoke-WebRequest -Uri "http://blogs.msdn.com/b/powershell/rss.aspx“$a.rss.channel.Item | select title,pubdate

功能很強(qiáng)大,使用卻很簡(jiǎn)單。
本文出自 “麻婆豆腐” 博客
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信