使用带有IE COM的Powershell的InsertAdjacentHtml



我正试图通过Powershell将InsertAdjacentHtml与IE COM一起使用,但我的代码失败了,原因是什么?

$oIE = new-object -ComObject InternetExplorer.Application
$oIE.visible=$True
$oIE.navigate2("http://www.quirksmode.org/dom/core/getElementsByName.html")
While ($ie.Busy) {
Sleep 2
}
$doc = $oIE.Document
$btns = $doc.getElementsByTagName("input")
$btns.insertAdjacentHTML('afterend', '<div id="secondDiv">Second</div>');
$oIE.visible=$True

命令行显示无效操作错误

我逐行运行了您的脚本,并将其保存为PowerShell脚本,但得到了不同的结果-两者都是错误。

当逐行运行时,我会收到以下错误:

Method invocation failed because [System.__ComObject] does not contain a method named 'insertAdjacentHTML'.
At line:1 char:1
+ $btns.insertAdjacentHTML('afterend', '<div id="secondDiv">Second</div>');
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (insertAdjacentHTML:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

尽管方法"insertAdjacentHTML"与Get Member一起列出,但不能使用。

所以,我想找到一个原因,或者另一种方式来实现同样的事情。我最终得出了这样的结论:PowerShell可能不是实现您正在尝试的目标的最佳工具,或者您应该使用具有更可靠方法的对象。

当我逐行运行一个修改过的脚本时,它有点工作:

$oIE = new-object -ComObject InternetExplorer.Application
$oIE.visible=$True
$oIE.navigate2("http://www.quirksmode.org/dom/core/getElementsByName.html")
$doc = $oIE.Document
$btn = $doc.all.item("test", 1)
$btn.insertAdjacentHTML('afterend', '<div id="secondDiv">Second</div>')
$oIE.visible=$True


这是HTML生成的:

<div id="test">
    <p name="test">This is a paragraph with name="test"</p>
    <ppk name="test">This is a ppk tag with name="test"</ppk>
    <p><input name="test"><div id="secondDiv">Second</div>This is an input with name="test"</p>
    <p><img name="test">This is an image with name="test"</p>
</div>


更奇怪的是,这只适用于普通的PowerShell控制台,在使用PowerShell ISE时会失败。


编辑:试试ForEach循环,它可能会起作用。我突然想到,除非在循环中调用某个方法,否则无法在对象数组上运行该方法。另外,脚本导航到的页面可能存在问题。

所以,这是有效的:

$oIE = new-object -ComObject InternetExplorer.Application
$oIE.visible = $True
$oIE.navigate2("https://stackoverflow.com/questions/28650033/use-insertadjacenthtml-by-powershell-with-ie-com/")
Start-Sleep -Milliseconds 3333
$doc = $oIE.Document
$btns = $doc.getElementsByName("_id_")
$btns | ForEach-Object { $_.insertAdjacentHTML('afterend', '<div id="secondDiv">Second</div>') }

谢谢你的提问,很高兴知道。

最新更新