因此,我尝试从网站获取一些文本,一旦我尝试使用 ParsedHtml 返回对象,powershell 就会停止响应(即使我让它在后台运行几分钟,它也不会再执行任何操作)。
造成这种情况的原因是什么?
PS P:\> $url = "mywebsite"
PS P:\> $result = invoke-WebRequest $url
PS P:\> $result | Get-Member
TypeName: Microsoft.PowerShell.Commands.HtmlWebResponseObject
Name MemberType Definition
---- ---------- ----------
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
AllElements Property
Microsoft.PowerShell.Commands.WebCmdletElementCollection AllElements {get;}
BaseResponse Property System.Net.WebResponse BaseResponse {get;set;}
Content Property string Content {get;}
Forms Property
Microsoft.PowerShell.Commands.FormObjectCollection Forms {get;}
Headers Property
System.Collections.Generic.Dictionary[string,string] Headers {get;}
Images Property
Microsoft.PowerShell.Commands.WebCmdletElementCollection Images {get;}
InputFields Property
Microsoft.PowerShell.Commands.WebCmdletElementCollection InputFields {get;}
Links Property
Microsoft.PowerShell.Commands.WebCmdletElementCollection Links {get;}
ParsedHtml Property mshtml.IHTMLDocument2 ParsedHtml {get;}
RawContent Property string RawContent {get;set;}
RawContentLength Property long RawContentLength {get;}
RawContentStream Property System.IO.MemoryStream RawContentStream {get;}
Scripts Property
Microsoft.PowerShell.Commands.WebCmdletElementCollection Scripts {get;}
StatusCode Property int StatusCode {get;}
StatusDescription Property string StatusDescription {get;}
PS P:\> $result.ParsedHtml | Get-Member
然后程序在最后一个命令后冻结。
弹出一个窗口询问我是否允许在我的电脑上保存cookie,但单击“是”或“否”都没有任何帮助。
这可能是什么原因造成的?
$result.RawContent
例如工作得很好并打印出所有的 html 文本,但没有 getelementsby-Method,我猜它在 ParsedHtml 中,因此为什么我需要它..它可以在 youtube 上工作,但在我想要的特定网站上检查它是否冻结。
任何帮助是极大的赞赏!
From learn.microsoft.com 上的 Invoke-WebRequest 参考页面:
该参数已被弃用。从 PowerShell 6.0.0 开始,
所有 Web 请求仅使用基本解析。包含此参数
仅用于向后兼容,任何使用它都不会影响
cmdlet 的操作。
以及 MS 工作人员评论的更详细解释PowerShell Github 存储库问题 #2867:
Windows PowerShell 依赖 Internet Explorer 来解析 html。
由于 Internet Explorer 在我们支持的大多数平台上不可用
使用 PowerShell Core 6(nanoserver、Linux、macOS),有意义
默认为-UseBasicParsing。 @MSAdministrator 的建议
ConvertFrom-Html 是一个更好的解决方案,而不是与解析结合
Web cmdlet 的功能(例如解析本地 html 文件)。
然后:
社区似乎已经通过 PowerShellGallery 上的模块来帮助填补这一空白,以专门处理解析 html。
今天似乎没有 ConvertFrom-Html,所以我猜你的选择是:提供解析的 PowerShell Gallery 模块,或者下面是有限的替代方案。看起来他们不会为您提供 ParsedHTML 属性本身,但它们确实为您提供了一些可遍历/结构化的内容might服务于您的目的:
https://stackoverflow.com/a/53878303/537243
在非常非常有限的情况下,您可以尝试使用“html 是 xml 的子类型”的方式,但是 xml 解析器会因 html 中允许的许多语法“偏差”而感到困惑并失败,因此源代码必须非常有规律且非常普通:
$webresponse = Invoke-WebRequest -Uri "https://w3.org"
$xmldoc = [xml]$webresponse.Content
write-output $xmldoc.html.body.div[0].div.h1.span |select '#text'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)