当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

作者:精品下载站 日期:2024-12-14 04:55:41 浏览:15 分类:玩电脑

PowerShell 调用-Webrequest |自动执行 API 的 Web 请求


[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

PowerShell Invoke-Webrequest 的定义

在 PowerShell 中,Invoke-WebRequest cmdlet(属于 Microsoft.PowerShell.Utility Module 的一部分)是发送 HTTP 的 Web 抓取方法之一(另一种方法是 Invoke-RestMethod,在 cmd 和其他操作系统中称为 CURL) HTTPS 请求到所请求的网页或 URI,称为端点,并以标题、图像、链接和其他 HTML 重要元素的形式检索、删除、更新内容,为此它使用多种方法,如 GET、POST、PUT、 DELETE等发送请求、修改内容或删除网页内容。 Invoke-WebRequest 也可以与 REST API 配合使用。

语法:

Invoke-WebRequest

[-UseBasicParsing]
[-Uri] <Uri>
[-WebSession <WebRequestSession>]
[-SessionVariable <String>]
[-AllowUnencryptedAuthentication]
[-Authentication <WebAuthenticationType>]
[-Credential <PSCredential>]
[-UseDefaultCredentials]
[-CertificateThumbprint <String>]
[-Certificate <X509Certificate>]
[-SkipCertificateCheck]
[-SslProtocol <WebSslProtocol>]
[-Token <SecureString>]
[-UserAgent <String>]
[-DisableKeepAlive]
[-TimeoutSec <Int32>]
[-Headers <IDictionary>]
[-MaximumRedirection <Int32>]
[-MaximumRetryCount <Int32>]
[-RetryIntervalSec <Int32>]
[-Method <WebRequestMethod>]
[-Proxy <Uri>]
[-NoProxy]
[-CustomMethod <String>]
[-ProxyCredential <PSCredential>]
[-ProxyUseDefaultCredentials]
[-Body <Object>]
[-Form <IDictionary>]
[-ContentType <String>]
[-TransferEncoding <String>]
[-InFile <String>]
[-OutFile <String>]
[-PassThru]
[-Resume]
[-SkipHttpErrorCheck]
[-PreserveAuthorizationOnRedirect]
[-SkipHeaderValidation]
[<CommonParameters>]

Invoke-WebRequest 方法在 PowerShell 中如何工作?

从 PowerShell v3.0 开始,PowerShell 添加了 cmdlet Invoke-WebRequest,该 cmdlet 随 Microsoft.PowerShell.Utility 模块一起提供以处理网页。我们可以使用 PowerShell 检索、删除或更新网页内容。显然,这与使用 GUI 进行页面导航的体验不同,但它是为了自动化 Web 请求并摆脱繁琐的浏览和日常手动任务。

Invoke-WebRequest 向 URI(统一资源标识符)(也称为端点)发送请求,并从网页检索数据。它直接使用 URL 或 REST API,因为某些网站允许仅使用 API 修改内容。

当我们使用 API 时,输出数据通常采用 JSON 或 XML 格式。例如,

https://yts.mx/api/v2/list_movies.json

或者

https://yts.mx/api/v2/list_movies.xml

在上述情况下,一旦检索到内容,我们就可以使用 PowerShell 将内容转换为 JSON 或 XML 方法。

示例

让我们讨论 PowerShell Invoke-Webrequest 的示例。

a.Invoke-WebRequest 从网页检索数据。

我们可以提供 URI 以从网页检索内容。有一个 Content 和 RawContent 属性,您可以使用这些属性来检索数据。这取决于网页以及我们正在检索的数据类型。数据可以是 HTML 格式,也可以是 JSON 或 XML 格式。

$req = Invoke-WebRequest -Uri https://theautomationcode.com/feed/
$req

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

运行上述命令后,您可以看到不同的属性,例如 StatusCode、StatusDescription、Content、RawContent、Forms、Headers、Images、InputFields、Links、ParsedHtml、RawContentLength 等。

您还可以使用 Get-Member 命令检查此命令的属性。

$req | gm -MemberType Properties

输出:

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

要检索内容,

$req = Invoke-WebRequest -Uri "https://theautomationcode.com/feed/"
$req.Content

b.调用-WebRequest检查网站状态代码。

当客户端向端点发送请求时,它会发送带有各种状态代码的握手状态,该状态代码显示网站可用性或网页上的任何错误。

您可以在链接下方找到各种代码及其状态消息。

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

要使用 Invoke-WebRequest 检索状态消息,我们需要使用 StatusCode 作为引用属性。例如,

try{
$uri = "http://theautomationcode.com"
$response = Invoke-WebRequest -Uri $uri -Method Get -ErrorAction Stop
Write-Output "Status Code : $($response.statuscode)"
}
catch{
Write-Output "Status Code : $($_.Exception.Response.StatusCode.Value__)"
}

输出:

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

如果我们提到一个不存在的网站,它会给出不同的状态代码。对于以下 URI,

$uri = "http://theautomationcode.com/failed"

输出:

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

c.调用-WebRequest 从网页检索图像和链接。

我们可以使用 Invoke-WebRequest 命令从网页检索图像和链接。要从网页中检索图像并将其存储在特定位置,请使用以下命令:

try{
$wc = New-Object System.Net.WebClient
$uri = "http://theautomationcode.com"
$imgs = (Invoke-WebRequest -Uri $uri -ErrorAction Stop).Images
$count = 0
foreach($imgurl in $imgs.src){
$wc.DownloadFile($imgurl,"C:\temp\WebImages\img$Count.jpg")
$count++
}
}
catch{
Write-Output "Status Code : $($_.Exception.Response.StatusCode.Value__)"
}

输出:

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

Invoke-WebRequest 从网页获取链接。

$uri = "http://theautomationcode.com"
$response = Invoke-WebRequest -Uri $uri
$response.Links.href

输出:

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

d.在 Invoke-Webrequest 中使用表单。

表单是存储有关输入项的信息(例如用户名和密码)的页面。我们可以使用表单通过 POST 方法提交用户名和密码。

例如,我们将使用 Reddit 登录页面并在那里提交凭据。要检索登录页面,我们有以下 Reddit 的 URL。

$Response = Invoke-WebRequest https://www.reddit.com/login/ -SessionVariable sv
$Response.Forms

在这里,我们使用 Forms 属性来检索我们需要的信息。

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

运行上述命令后,您可以看到那里的 POST 方法,我们将使用它。

$Response = Invoke-WebRequest https://www.reddit.com/login/ -SessionVariable sv
$form = $Response.Forms[2]
$form.Fields['loginUsername'] = 'reddit'
$form.Fields['loginPassword'] = 'redditpass'
Invoke-WebRequest $Response -Body $form -WebSession $sv -Method Post

上面的脚本是 Web 表单和 POST 方法的示例。

e.调用-WebRequest 从网页获取提要。

有时我们只需要检索网页的内容。例如,来自网页的源可能采用 JSON 或 XML 格式。在下面的示例中,我们将从 URL https://www.reddit.com/.rss 检索 Reddit RSS 提要,然后将其转换为 XML 或 JSON 格式,以便以正确的方式检索提要在控制台中格式化。例如,

$response = Invoke-WebRequest "https://www.reddit.com/.rss" -Method Get
$response.Content

一旦我们运行上述命令,它就会检索 XML 输出,如下所示。

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

$response = Invoke-WebRequest "https://www.reddit.com/.rss" -Method Get
$feeds = [XML]$response.Content | Select -ExpandProperty Feed
$feeds.Entry | Select Title, Updated

输出:

[玩转系统] PowerShell 调用-Webrequest |自动执行 API 的 Web 请求

结论

Invoke-Webrequest 是一个非常有用的命令,用于自动化 Web 请求和使用 API。有许多免费的 API,例如天气 API、电影数据库和金融 API,可以与 Web 请求集成,在这种情况下,我们可以从请求的 API 中检索、更新、发布或删除数据。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯