vb.net 教程 12-3 HtmlElement類 6


經過上面兩節的學習,我們已經可以做到填充數據和提交表單了。

作為一個自動填表軟件,自然需要同時完成以上兩方面的功能。

簡單的是我們可以直接將兩段代碼合並在一起:

    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 = "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 教程 目錄




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com