PowerShell实现IE Web自动化

使用IE的COM对象来完成简单的Web自动化测试,是最小巧和廉价的Web自动化测试了,因为它不用引入第三方插件或者工具。Windows 系统自带的Internet Explore +加上PowerShell 即可搞定。

今天就分享下这几天自己写的几个小函数,欢迎拍砖:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#
# 打开IE窗口
#
function New-IEWindow
{
    param (
    [string] $Url ,
    [switch] $Visible ,
    [switch] $FullScreen
    )
    $Global:IEHost new-object -com "InternetExplorer.Application"
    $Global:IEHost .Navigate( $Url )
  
    #设置IE可见性和全屏
    $Global:IEhost .Visible=  $Visible
    $Global:IEHost .FullScreen=  $FullScreen
     
}
 
#
#等待IE加载完毕
#
function Wait-IEReady ( [int] $TimeoutSeconds =10)
{
     $milliseconds =0
     $maxMilliseconds $TimeoutSeconds * 1000
     while ( $Global:IEHost .Busy)
     {
        
       if ( $milliseconds -gt $maxMilliseconds )
       {
         throw  'Wait ie ready timeout.'
       }
       sleep -Milliseconds 100
       $milliseconds +=100
        
     }
}
 
#
# 根据ID,Class,Name,Tag获取HTML元素
#
function Get-HtmlElement ( $Id , $Name , $Class , $Tag )
{
   if ( $Id )
   {
     return $IEHost .Document.getElementById( $id )
   }
   elseif ( $Name )
   {
     return $IEHost .Document.getElementsByName( $Name )
   }
   elseif ( $Class )
   {
     $IEHost .Document.all | where { $_ .className  -contains $Class }
   }
   elseif ( $Tag )
   {
     $IEHost .Document.getElementsByTagName( $Tag )
   }
    
}
 
#
#关闭IE窗口
#
function Close-IEWindow
{
     $Global:IEHost .quit()
     Remove-Variable IEHost -Force
}
 
#
#设置IE的地址
#
function Navigate-IE( $Url )
{
  Set-IE -URL $Url
}
  
#
# 设置IE的地址,或者动作:前进,倒退,刷新
#
function Set-IE
{
  param (
  [ ValidateSet ( 'GoBack' 'GoForward' , 'Refresh' )]
  [string] $Action ,
  [uri] $URL
  )
  
  # 动作
  switch ( $Action )
  {
   ( 'GoBack' ){  $Global:IEHost .GoBack() }
   ( 'GoForward' ){   $Global:IEHost .GoForward() }
   ( 'Refresh' ){  $Global:IEHost .Refresh() }
  }
  
  # 设置IE地址
  if $URL ) {
  $Global:IEHost .Navigate( $URL ) }
}
  
#
# 在IE窗口中执行脚本
#
function Invoke-IEScript ( $Code , $Language = 'Javascript' )
{
  if -not [string] ::IsNullOrWhiteSpace( $Code ))
  {
   $Global:IEHost .Document.parentWindow.execScript( $Code , $Language )
  }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值