HTML
<a onclick="loadYearPage('2018-2019')" style="cursor: pointer;">2018-2019</a>
如何使用CSS选择器定位元素onclick
我尝试了以下代码,但无法正常工作
ie.document.querySelector("[onclick='loadYearPage('2018-2019')']").Click
请建议
答案 0 :(得分:2)
蒂姆的答案是我的偏爱,因为它很好地逃脱了。您还可以使用不同的运算符指定多个css attribute =值选择器,并组合为And语法
ie.document.querySelector("a[onclick^=loadYearPage][onclick*='2018-2019']")
如果这些子字符串中的任何一个仅在页面上出现一次,则可以减少该字符,例如
ie.document.querySelector("a[onclick*='2018-2019']")
使用您提供的页面,您确实可以使用contains修饰符(*)在onclick
属性值中按部分字符串进行搜索。下面是一个可以将年份作为变量传递的示例。我已经选择了较短的选择器以提高速度。需要稍等一会儿,该元素才会出现。我使用了定时循环。
Option Explicit
'https://www.nseindia.com/products/content/derivatives/currency/cd_historical_businessGrowth.htm
Public Sub PerformClick()
Dim ie As InternetExplorer, t As Date, ele As Object
Const MAX_WAIT_SEC As Long = 10
Set ie = New InternetExplorer
Dim yearSelection As String
yearSelection = "2018-2019"
With ie
.Visible = True
.Navigate2 "https://www.nseindia.com/products/content/derivatives/currency/cd_historical_businessGrowth.htm"
While .Busy Or .readyState < 4: DoEvents: Wend
t = Timer
Do
On Error Resume Next
Set ele = .document.querySelector("[onclick*='" & yearSelection & "']")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing
If Not ele Is Nothing Then
ele.Click
While .Busy Or .readyState < 4: DoEvents: Wend
End If
'other code
Stop '<==Delete me later
.Quit
End With
End Sub
答案 1 :(得分:1)
这有效:
document.querySelector('a[onclick="loadYearPage(\'2018-2019\')"]')