订阅专栏
版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
经过上面两节的学习,我们已经可以做到填充数据和提交表单了。
作为一个自动填表软件,自然需要同时完成以上两方面的功能。
简单的是我们可以直接将两段代码合并在一起:
Private Sub btnOneKey1_Click(sender As Object, e As EventArgs) Handles btnOneKey1.Click
Dim strName As String = "张三"
Dim strAge As String = "12"
Dim htmlAlls As HtmlElementCollection
htmlAlls = wbMain.Document.All
For Each htmlSingle As HtmlElement In htmlAlls
Select Case htmlSingle.GetAttribute("name")
Case "studentname"
htmlSingle.SetAttribute("value", strName)
Case "studentage"
htmlSingle.SetAttribute("value", strAge)
Case Else
'不处理
End Select
Next
For Each htmlSingle As HtmlElement In htmlAlls
Select Case htmlSingle.GetAttribute("name")
Case "submit1"
htmlSingle.RaiseEvent("onclick")
Case Else
'不处理
End Select
Next
End Sub
当然代码会遍历了网页内的所有元素,但实际上我们只需要Input标签的数据。
那么可以将
htmlAlls = wbMain.Document.All
修改为:
htmlAlls = wbMain.Document.GetElementsByTagName("Input")
完整代码:
Private Sub btnOneKey2_Click(sender As Object, e As EventArgs) Handles btnOneKey2.Click
Dim strName As String = "李四"
Dim strAge As String = "https://files.jxasp.com/image/21"
Dim htmlAlls As HtmlElementCollection
htmlAlls = wbMain.Document.GetElementsByTagName("Input")
For Each htmlSingle As HtmlElement In htmlAlls
Select Case htmlSingle.GetAttribute("name")
Case "studentname"
htmlSingle.SetAttribute("value", strName)
Case "studentage"
htmlSingle.SetAttribute("value", strAge)
Case Else
'不处理
End Select
Next
For Each htmlSingle As HtmlElement In htmlAlls
Select Case htmlSingle.GetAttribute("name")
Case "submit1"
htmlSingle.RaiseEvent("onclick")
Case Else
'不处理
End Select
Next
End Sub
还是需要两次枚举,因为我们不能在数据没有填充完之前就提交。
那么,还可以采用一种指定对象的方法:HtmlDocument.GetElementById(),参数为网页元素的ID,通常这个是不重复的。
具体代码如下:
Private Sub btnOneKey3_Click(sender As Object, e As EventArgs) Handles btnOneKey3.Click
Dim strName As String = "王五"
Dim strAge As String = "7"
Dim htmlName As HtmlElement
htmlName = wbMain.Document.GetElementById("studentname")
htmlName.SetAttribute("value", strName)
Dim htmlAge As HtmlElement
htmlAge = wbMain.Document.GetElementById("studentage")
htmlAge.SetAttribute("value", strAge)
Dim htmlSubmit As HtmlElement
htmlSubmit = wbMain.Document.GetElementById("submit1")
htmlSubmit.RaiseEvent("onclick")
End Sub
运行效果如下:
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net教程 目录
————————————————
版权声明:本文为CSDN博主「VB.Net」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。