问题
I am using excel VBA to open this website: Legal and General, Then it needs to click the "Fund prices and charges" button.
Inspecting the web page with chrome, I can see this button has the following code:
<div class=" selected tab" tabindex ="0" role="button" aria-pressed="true">...</div>
The HTML 'view source' suggests a script type="application/JSON"
I'm very confused by all of this. Does anyone know how I can select this button? I have this section of code so far:
Set HTMLDoc = .document
Set objElement = HTMLDoc.getElementsByClassName("Select - Tab - Fund prices and charges")(0)
objElement.Click
.Quit
Any help will be much appreciated.
Regards
Dave
回答1:
If only interested in that one tab I would first grab the parent element (div), which houses all the tabs, by its classname using a css class selector. I would then use a child combinator in combination with nth-child() selector to grab the second child div by its classname:
.querySelector(".table-view__tabs > div:nth-child(2)").Click 'Select tab direct
If potentially interested in all 3 tabs:
I would first grab the parent element (div), which houses all the tabs, by its classname using a css class selector. I would then use a child combinator to grab the child divs (which are the tabs) by their classnames. I would index into the returned nodeList to click the required tab:
Set tabs = .querySelectorAll(".table-view__tabs > div") 'select all tabs then index in for tab of choice
tabs.Item(1).Click
VBA:
Option Explicit
Public Sub ClickButton()
Dim ie As SHDocVw.InternetExplorer
Set ie = New SHDocVw.InternetExplorer
With ie
.Visible = True
.Navigate2 "https://fundcentres.lgim.com/uk/workplace-employee/fund-centre/#Product=WorkSave-Pension-Plan-(generation-3)"
While .Busy Or .ReadyState <> 4: DoEvents: Wend
With .Document
.querySelector(".table-view__tabs > div:nth-child(2)").Click 'Select tab direct
Stop 'Delete me later
Dim tabs As Object
Set tabs = .querySelectorAll(".table-view__tabs > div") 'select all tabs then index in for tab of choice
tabs.Item(1).Click '0 based so first tab is 0, second is 1 etc
Stop 'Delete me later
End With
Stop '<==Delete me later
.Quit
End With
End Sub
Reading:
- CSS selectors
- Child combinator
- Class selector
- :nth-child
- document.querySelectorAll
- document.querySelector
References (VBE>Tools>References):
- Microsoft Internet Controls
来源:https://stackoverflow.com/questions/59395660/excel-vba-click-website-button-with-no-name-or-id-that-uses-json