【发布时间】:2019-12-14 09:35:55
【问题描述】:
以下 Powershell 脚本运行 Google 搜索存储在我的硬盘中的图像。
我怎样才能获得进入结果页面的链接?是否可以导航到其上显示的不同网页?
我尝试$request.Links | Select href 尝试获取链接列表,但没有成功。我也尝试将Write-Output $respStream 添加到代码中,但它没有运行。
Set-ExecutionPolicy Bypass -scope Process -Force
function Get-GoogleImageSearchUrl
{
param(
[Parameter(Mandatory = $true)]
[ValidateScript({ Test-Path $_ })]
[string] $ImagePath
)
# extract the image file name, without path
$fileName = Split-Path $imagePath -Leaf
# the request body has some boilerplate before the raw image bytes (part1) and some after (part2)
# note that $filename is included in part1
$part1 = @"
-----------------------------7dd2db3297c2202
Content-Disposition: form-data; name="encoded_image"; filename="$fileName"
Content-Type: image/jpeg
"@
$part2 = @"
-----------------------------7dd2db3297c2202
Content-Disposition: form-data; name="image_content"
-----------------------------7dd2db3297c2202--
"@
# grab the raw bytes composing the image file
$imageBytes = [Io.File]::ReadAllBytes($imagePath)
# the request body should sandwich the image bytes between the 2 boilerplate blocks
$encoding = New-Object Text.ASCIIEncoding
$data = $encoding.GetBytes($part1) + $imageBytes + $encoding.GetBytes($part2)
# create the HTTP request, populate headers
$request = [Net.HttpWebRequest] ([Net.HttpWebRequest]::Create('http://images.google.com/searchbyimage/upload'))
$request.Method = "POST"
$request.ContentType = 'multipart/form-data; boundary=---------------------------7dd2db3297c2202' # must match the delimiter in the body, above
$request.ContentLength = $data.Length
# don't automatically redirect to the results page, just take the response which points to it
$request.AllowAutoredirect = $false
# populate the request body
$stream = $request.GetRequestStream()
$stream.Write($data, 0, $data.Length)
$stream.Close()
# get response stream, which should contain a 302 redirect to the results page
$respStream = $request.GetResponse().GetResponseStream()
# pluck out the results page link that you would otherwise be redirected to
(New-Object Io.StreamReader $respStream).ReadToEnd() -match 'HREF\="([^"]+)"' | Out-Null
$matches[1]
}
$url = Get-GoogleImageSearchUrl "C:\Users\Path\filename.jpeg"
Start-Process $url
【问题讨论】:
-
您是否尝试获取
302重定向到的URL?如果是这样,请改为阅读响应的Location标头。 -
你为什么使用
[Net.HttpWebRequest]而不是Invoke-WebRequest来发出网络请求?这不一定能解决您的问题,但可以引导您朝着正确的方向前进