.mht 保存网页中的 DOM 遍历



是否可以在保存为.mht或另存为.htm(仅限html)的网页中进行DOM遍历?
最好在Powershell或.net
中目标是能够做类似getElementsByTagName('div')
的事情如果是,如何?

使用 HtmlAgilityPack 找到了解决方案。
文档可以在NuDoq上找到,这篇文章中提到了这一点。

示例代码:

# Choose a source
$Source = 'C:tempmyFile.mht'
$Source = 'http://www.google.com'
# Get online or mht content
$IE = New-Object -ComObject InternetExplorer.Application
# Don't show the browser
$IE.Visible = $false
# Browse to your webpage/file
$IE.Navigate($Source)
# Wait for page to load
while ($IE.busy) { Sleep -Milliseconds 50 }
# Get the html from that page
$Html = $IE.Document.body.parentElement.outerHTML
# Decode to get rid of html encoded characters like & etc...
$Html = [System.Web.HttpUtility]::HtmlDecode($Html)
# Close the browser
$IE.Quit()

# Use HtmlAgilityPack (must be installed first)
Add-Type -Path (Join-Path $Env:userprofile '.nugetpackageshtmlagilitypack1.4.9.5libNet40HtmlAgilityPack.dll')
$Hap = New-Object HtmlAgilityPack.HtmlDocument
# Load the Html in HtmlAgilityPack to get a DOM
$Hap.LoadHtml($global:Html)
# Retrieve the data from the DOM (read a node)
[string]$partData = $Hap.DocumentNode.SelectSingleNode("//div[@class='formatted_content']/ul").InnerText

最新更新