powershell网络蜘蛛解决乱码问题

所属分类: 脚本专栏 / PowerShell 阅读数: 1461
收藏 0 赞 0 分享

抓取(爬取)网上信息的脚本程序,俗称网络蜘蛛。
powershell中自带了这样的两个命令,【Invoke-WebRequest】和【Invoke-RestMethod】,但这两个命令有时候会乱码。

现在转帖分享, 某个【歪果仁】写的脚本。来源于 墙外出处: https://gist.github.com/angel-vladov/9482676

核心代码

function Read-HtmlPage {
param ([Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)][String] $Uri)

# Invoke-WebRequest and Invoke-RestMethod can't work properly with UTF-8 Response so we need to do things this way.
[Net.HttpWebRequest]$WebRequest = [Net.WebRequest]::Create($Uri)
[Net.HttpWebResponse]$WebResponse = $WebRequest.GetResponse()
$Reader = New-Object IO.StreamReader($WebResponse.GetResponseStream())
$Response = $Reader.ReadToEnd()
$Reader.Close()

# Create the document class
[mshtml.HTMLDocumentClass] $Doc = New-Object -com "HTMLFILE"
$Doc.IHTMLDocument2_write($Response)

# Returns a HTMLDocumentClass instance just like Invoke-WebRequest ParsedHtml
$Doc

#powershell 传教士 转帖并修改的文章 2016-01-01, 允许再次转载,但必须保留名字和出处,否则追究法律责任

}

原文函数

function Read-HtmlPage {
  param ([Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)][String] $Uri)

  # Invoke-WebRequest and Invoke-RestMethod can't work properly with UTF-8 Response so we need to do things this way.
  [Net.HttpWebRequest]$WebRequest = [Net.WebRequest]::Create($Uri)
  [Net.HttpWebResponse]$WebResponse = $WebRequest.GetResponse()
  $Reader = New-Object IO.StreamReader($WebResponse.GetResponseStream())
  $Response = $Reader.ReadToEnd()
  $Reader.Close()

  # Create the document class
  [mshtml.HTMLDocumentClass] $Doc = New-Object -com "HTMLFILE"
  $Doc.IHTMLDocument2_write($Response)
  
  # Returns a HTMLDocumentClass instance just like Invoke-WebRequest ParsedHtml
  $Doc
}

PowerShell function you can use for reading UTF8 encoded HTML pages content. The built in Invoke-WebRequest and Invoke-RestMethod fail miserably.

更多精彩内容其他人还在看

PowerShell操作Excel、CSV详细介绍

这篇文章主要介绍了PowerShell操作Excel、CSV详解,本文比较深入的探讨了PowerShell中如何操作Excel及CSV,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell中显示隐藏文件的方法

这篇文章主要介绍了Powershell中显示隐藏文件的方法,本文使用是是Get-ChildItem检索文件,加上-Hidden参数就可以显示隐藏文件了,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中iso8601格式日期和DateTime对象互转实例

这篇文章主要介绍了PowerShell中iso8601格式日期和DateTime对象互转实例,本文讲解了iso8601格式转换成DateTime对象、日期时间转换成iso8601格式两个方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell使用C#实现缩写路径

这篇文章主要介绍了Powershell使用C#实现缩写路径,缩写路径有时候是非常有用的,比如某些报表的路径太长会很难看,缩写后就会好看许多,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell截取字符串并添加省略号的例子

这篇文章主要介绍了Powershell截取字符串并添加省略号的例子,本文直接给出代码实例,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell读取本机注册表中的所有软件关联扩展名

这篇文章主要介绍了Powershell读取本机注册表中的所有软件关联扩展名,本文直接给出实现代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell实现按类型排序

这篇文章主要介绍了Powershell实现按类型排序,本文直接给出实现代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell中打开网页实例

这篇文章主要介绍了Powershell中打开网页实例,本文直接给出实现代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell实现获取进程所有者

这篇文章主要介绍了PowerShell实现获取进程所有者,本文直接给出实现代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Windows Powershell Foreach 循环

Foreach-object 为cmdlet命令,使用在管道中,对管道结果逐个处理,foreach为遍历集合的关键字。
收藏 0 赞 0 分享
查看更多