【问题标题】:PowerShell: write value in a input type=file Form.PowerShell:在输入类型=文件表单中写入值。
【发布时间】:2010-02-04 10:23:16
【问题描述】:

我在加载的网页上有一个 input type=text 输入框并填充了值,然后单击提交按钮,效果很好:

$ie=New-Object -comobject InternetExplorer.Application 
$ie.visible=$true 
$ie.Navigate("https://myurl/test.html") 
while($ie.busy){Start-Sleep 1} 
$ie.Document.getElementById("field_firstName").value="Firstname" 
$ie.Document.getElementById("field_lastName").value="Lastname" 
$ie.Document.getElementById("btn_upload").Click() 
while($ie.busy){Start-Sleep 1}

我还想用 c:\temp\test.txt 填充 input type=file 框并上传。 我读到由于安全原因,浏览器不支持 value=。

是否有任何解决方法可以使用 PowerShell 执行此操作? 也许“单击”浏览按钮并选择文件或使用发送键?

【问题讨论】:

    标签: html internet-explorer powershell file-upload input


    【解决方案1】:

    检查Jaykul's post。他使用 Watin 进行自动化。只需下载程序集并尝试。我能够设置值,然后像这样提交表单:

    $WatinPath = 'c:\bin\watin\WatiN.Core.dll' #path with downloaded assembly
    $watin     = [Reflection.Assembly]::LoadFrom( $WatinPath )
    
    $ie        = new-object WatiN.Core.IE("https://myurl/test.html")
    $file1 = $ie.FileUpload('file1') #id of the input
    $file1.set('C:\temp\test.txt') # path to the file
    
    # and now just find the button and click on it
    $o = $ie.Button('send') #send is id of the submit button
    $o.Click()
    

    我理解您使用 IE 而不是 WebClient 和类似类的原因,但如果可能,请在其他情况下使用它们。

    编辑:

    如果你没有元素的ID,只有名字,你可以试试

    $f = $ie.FileUpload({param($fu) $fu.GetAttributeValue("name") -eq 'the name you have' })
    

    $f = $ie.FileUploads | ? { $_.GetAttributeValue("name") -eq 'the name you have' }
    

    【讨论】:

    • 这看起来不错,虽然我无法找到正确的字段,因为源没有 id 而只是一个名字......你知道我是否可以按名字而不是 id 搜索吗?跨度>
    • 我使用了您调用函数 getElementById 的示例,所以我认为您知道 id。我会检查是否可以。
    • 我也很困惑为什么我的第一个示例有效,因为在那里我也只有一个名称而没有 id 标签...对于您的最后一个示例 $_.GetAttributeValue("name") 似乎我发现该框,但我的提交按钮(也没有 id 只是名称)没有工作。明天必须再玩一次。到目前为止谢谢你
    • 您必须像文件上传一样找到提交按钮:$sub = $ie.Button({param($fu) $t.GetAttributeValue("name") -eq 'name of submit button' }) 我不知道确切,我现在无法检查它。试试$ie | gm,你会找到正确的方法;)
    • 这成功了!谢谢!在我找到的 watin 列表中: ie.FileUpload(Find.ByName("ctl02$myfile")).Set("test.txt) 但我无法让 Find.ByName 工作.. 我会为您提供建议的解决方案现在。
    【解决方案2】:

    我强烈考虑使用WebClientHttpWebRequest,而不是驱动IE GUI。有一个使用 PowerShell 的WebClient example

    【讨论】:

    • 感谢您的回复,马修。虽然我现在更喜欢 IE Gui,因为我可以看到结果并避免代理证书等问题。我很想知道上面发布的代码在 webclient 方法中的样子..
    • 看起来你可能无法用纯 WebClient 做你想做的事。您可以查看 CodeProject (codeproject.com/KB/cs/uploadfileex.aspx) 中的一个函数。它基本上是一个更复杂的 WebClient.UploadFile 版本,基于 HttpWebRequest。
    【解决方案3】:

    是的,如果您想在 IE 中执行此操作,则必须使用 SendKeys 路由。在 IE8 及更高版本中,直接向框中输入文本是被阻止的。

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2021-02-25
      • 2015-05-08
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      相关资源
      最近更新 更多