Ricky

链接

RSS

RSS Link
NPM配置全局安装目录及使用淘宝源
搭建环境遇到的一系列问题

Powershell操作IE实现网站登录

Ricky posted @ 2017年8月16日 09:15 in Other , 1530 阅读

虽然curl也可以实现,但由于网站有cookies,偶尔会失败,所以研究了用Powershell控制IE模拟人操作实现网站登录认证

$url = "http://web.com/login.html" 
$username="username"
$password="password"
$ie = new-object -com "InternetExplorer.ApplicationMedium"
$ie.visible=$false
$ie.navigate("$url")
while($ie.ReadyState -ne 4) {start-sleep -m 100}
$ie.Document.IHTMLDocument3_getElementById("account").value = $username
$ie.Document.IHTMLDocument3_getElementById("acc_pass").value = $password
$ie.Document.IHTMLDocument3_getElementById("account_login_checkbox").checked=$true
$ie.Document.IHTMLDocument3_getElementById("account_login_btn").click()
start-sleep -m 1000
$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)
Remove-Variable ie

while($ie.ReadyState -ne 4) {start-sleep -m 100} 这句是控制等待IE载入页面

如果缺少这三行,会导致对象没有完全清理,再次运行脚本会报错计划关机已设置无法创建对象
$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)
Remove-Variable ie

由于Windows 11下powershell通过ID获取网页元素存在问题,通过$ie = new-object -com "InternetExplorer.ApplicationMedium"可以解决,但首先要在注册表新增默认值

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\InternetExplorer.ApplicationMedium]

[HKEY_CLASSES_ROOT\InternetExplorer.ApplicationMedium\CLSID] 
@="{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}"
 
并且只能通过$ie.Document.IHTMLDocument3_getElementById()这种方式获取页面元素
另外需要在兼容性视图设置中取消两个复选框。
 

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter