【问题标题】:How do I use 'getelementsbyclassname' when there's a number of the same class name?当有多个相同的类名时,如何使用“getelementsbyclassname”?
【发布时间】:2019-10-01 05:53:21
【问题描述】:
【问题讨论】:
标签:
vba
internet-explorer
web-scraping
getelementsbyclassname
【解决方案1】:
尝试参考下面的示例代码可能会帮助您找到内部文本 = 15,550。
Sub demo()
Dim element As IHTMLElement
Dim elements As IHTMLElementCollection
Dim ie As InternetExplorer
Dim val, val1 As String
Dim html As HTMLDocument
val = "15,550"
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate "https://finance.naver.com/item/sise_day.nhn?code=063760"
'Wait until IE has loaded the web page
Do While ie.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
Set html = ie.document
Set elements = html.getElementsByClassName("tah p11")
Dim count As Long
Dim erow As Long
count = 1
For Each element In elements
If element.className = "tah p11" Then
erow = Sheet1.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
val1 = html.getElementsByClassName("tah p11")(count).innerText
If val = val1 Then
Cells(erow, 1) = html.getElementsByClassName("tah p11")(count).innerText
End If
count = count + 1
End If
Next element
End Sub
输出:
这只是一个示例代码供您参考。此外,您可以尝试修改代码以获得所需的输出。
【解决方案2】:
在表格中定位时,通过nth-of-type css 选择器使用行和列索引。你想要第 4 行,第 2 列。鉴于现代网站为此进行了优化,我使用 css 选择器作为一种更快的方法。
ie.document.querySelector(".type2 tr:nth-of-type(4) td:nth-of-type(2)").innerText
你可以简单地缩短为
tr:nth-of-type(4) td:nth-of-type(2)
作为页面上具有此坐标的第一个表格。
我没有看到任何有用的信息,但也许还可以查看APIs。