使用Powershell的InsertAdjacentHtml和IE COM

时间:2015-02-21 19:02:40

标签: powershell

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

$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

命令行显示无效操作错误

1 个答案:

答案 0 :(得分:0)

我逐行运行你的脚本并将其保存为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

尽管方法&#39; insertAdjacentHTML&#39;与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>') }

感谢您提出这个问题,很高兴知道。