- 出于学习目的,可以选择具有更明显输入框而不是下拉菜单的网站。
- 许多输入框不会被预先填充,因此可以考虑读取检索到的元素的其他属性。甚至写信给他们,然后检索这些值。
- 按标签名称选择可以带回许多您可能没有预料到的项目。
牢记以上所有内容。尝试运行以下命令,生成<input> 标签元素的集合。
代码:
Option Explicit
Public Sub PrintTagInfo()
'Tools > references > Microsoft XML and HTML Object library
Dim http As New XMLHTTP60 '<== this will be specific to your excel version
Dim html As New HTMLDocument
With http
.Open "GET", "https://www.mrexcel.com/forum/register.php", False
.send
html.body.innerHTML = .responseText
End With
Dim inputBoxes As MSHTML.IHTMLElementCollection, iBox As MSHTML.IHTMLElement, i As Long
Set inputBoxes = html.getElementsByTagName("input") '<== the collection of input tags on the page
'<== These are input boxes i.e. you are putting info into them so perhaps populate and then try to read what is in the entry box?
For Each iBox In inputBoxes
Debug.Print "Result #" & i + 1
Debug.Print vbNewLine
Debug.Print "ID: " & iBox.ID '<== select a sample of properties to print out as some maybe empty
Debug.Print "ClassName: " & iBox.className,
Debug.Print "Title: " & iBox.Title
Debug.Print String$(20, Chr$(61))
Debug.Print vbNewLine
i = i + 1
Next iBox
End Sub
示例输出:
从上面看,如果您正在寻找目标框来输入信息,那么类名在某些方面可能会提供更多信息。
对页面源的初步检查、选择输入框并右键单击 > 检查...将帮助您优化选择。
我注意到很多感兴趣的盒子都有Input标签,然后是type = "text"
这意味着您可以使用CSS selectors 定位匹配此模式的元素。在这种情况下使用选择器input[type=""text""]。
调整以前的代码以将其考虑在内,从而产生更小、更有针对性的结果。注意,使用.querySelectorAll 来应用CSS 选择器会返回一个NodeList 对象,该对象需要不同的迭代方法。 For Each 循环将导致 Excel 崩溃,如 here 所述。
代码:
Option Explicit
Public Sub PrintTagInfo()
'Tools > references > Microsoft XML and HTML Object library
Dim http As New XMLHTTP60 '<== this will be specific to your excel version
Dim html As New HTMLDocument
With http
.Open "GET", "https://www.mrexcel.com/forum/register.php", False
.send
html.body.innerHTML = .responseText
End With
Dim inputBoxes As Object, i As Long
Set inputBoxes = html.querySelectorAll("input[type=""text""]") '<== the collection of text input boxes on page. Returned as a NodeList
'<== These are input boxes i.e. you are putting info into them so perhaps populate and then try to read what is in the entry box?
For i = 0 To inputBoxes.Length - 1
Debug.Print "Result #" & i + 1
Debug.Print vbNewLine
Debug.Print "ID: " & inputBoxes.Item(i).ID '<== select a sample of properties to print out as some maybe empty
Debug.Print "ClassName: " & inputBoxes.Item(i).className,
Debug.Print "Title: " & inputBoxes.Item(i).Title
Debug.Print String$(20, Chr$(61))
Debug.Print vbNewLine
Next i
End Sub
示例结果:
注意:我已经编辑了间距以更适合图像。
通过 VBE 添加的参考 > 工具 > 参考
最后两个是感兴趣的。底部的将是特定于版本的,如果不使用 Excel 2016,您将需要重新编写 XMLHTTP60,即 XML 6.0 以针对您的 Excel 版本。