我看到您对如何访问 HTML 元素有点困惑,所以我将借此机会以非常详细的方式演示这样做的逻辑,我也认为这非常直观。还有其他方法可以做到,但我相信以下一种是最全面和最直观的一种,非常适合初学者。
首先,我将继续假设ie3 是一个InternetExplorer 对象。
当您使用此对象导航到某个页面时,您可以使用包含HTML document 对象的ie3.document 访问该页面的html。
要充分利用HTML document 对象,您应该添加对Microsoft HTML Object Library 的引用。该库将允许您使用许多 HTML 元素,让您的生活更轻松。
在您的情况下,您希望能够访问的元素是
- HTML 表格及其行和单元格
- HTML 锚元素 ()
所以我的声明如下:
Dim ie3 As New InternetExplorer 'To be used to navigate to the page of interest
Dim doc As HTMLDocument 'this will hold the HTML document corresponding to the page
Dim toBeClicked As HTMLAnchorElement 'To be used to store the <a></a> element
Dim table As HTMLTable 'To be used to store the table element
Dim tableRow As HTMLTableRow 'To be used to store a row of the table element
Dim tableCell As HTMLTableCell 'To be used to store a cellof the table element
假设您已经使用 ie3 导航到感兴趣的网站,您可以将其 HTML 文档存储在 doc 中,如下所示:
Set doc = ie3.document
一旦您可以访问网页的 HTML 文档,您还可以通过多种方式访问其元素,其中一些方式比其他方式更有针对性。下面我以表格元素为例,演示最常用的方法。
如果表具有唯一 ID,则可以使用 .getElementById() 方法访问它。此方法返回单个元素。在您的情况下,您所使用的表没有 ID。
如果表属于某个类,则可以使用.getElementsByClassName() 方法访问它。这个方法返回一个元素的collection,所有这些元素都属于同一个类。要访问此集合的成员,您可以使用 (item index) 类型的符号。第一个成员的索引为0。在您的情况下,该表属于 "advancedSearch_table" 类,恰好只有一个成员。
- 如果没有类或 ID,您可以使用
.getElementsByTagName 方法。此方法返回具有相同标签的所有元素的集合。在您的情况下,您将需要文档中的所有表格。要访问此集合的成员,您可以使用 (item index) 类型的符号。第一个成员的索引为0。 HTML 中的标签看起来像 <tagName attribute="something">Something</tagName>。
下面我将演示所有三种方法。您可以使用前两种中的任何一种:
Set table = doc.getElementsByClassName("advancedSearch_table")(0)
Set table = doc.getElementsByTagName("table")(0)
Set table = doc.getElementById("ID of the table") 'only for demostration purposes, it doesn't apply to your case, as the table has no ID.
请记住,在您的情况下,文档中只有一个表格,并且只有一个元素属于 "advancedSearch_table" 类。这意味着您需要相应集合的第一个元素。这就是我使用0 作为索引的原因。
通过与上述相同的逻辑,现在表格已存储,您可以访问其行和单元格。更具体地说,您需要第 4 行的第 5 个单元格。这就是您要单击的链接所在的位置:
Set tableRow = table.getElementsByTagName("tr")(3)
Set tableCell = tableRow.getElementsByTagName("td")(4)
最后,既然感兴趣的单元格已存储,您可以访问锚元素并单击它。同样,单元格中只有一个锚元素,因此它将是相应集合中的第一个:
Set toBeClicked = tableCell.getElementsByTagName("a")(0)
toBeClicked.Click
奖金
如果你想一一点击所有的“完成”链接,你需要循环遍历相应的元素。这里有两种方法:
点击每行第5个单元格中的锚点:
For Each tableRow In table.Rows
Set toBeClicked = tableRow.getElementsByTagName("td")(4).getElementsByTagName("a")(0)
toBeClicked.Click
Next tableRow
遍历所有行和表格的所有单元格,找到您要查找的内部文本并单击相应的锚点:
For Each tableRow In table.Rows
For Each tableCell In tableRow.Cells
If tableCell.innerText = "Something" Then
Set toBeClicked = tableCell.getElementsByTagName("a")(0)
toBeClicked.Click
Next tableCell
Next tableRow