问题
Hi I am trying to create a script to click on a link of which I can provide a partial link. It would be great if someone may please advise how I can do this
<a href="website/report/download.json?refId=3e49762e-8edc-47c2-a282-11ee3c64e85a&reportType=xlsx&fileName=GeneralExtract.xlsx&obo>GeneralExtract.xlsx</a>
Set i = CreateObject("InternetExplorer.Application")
Dim idoc As MSHTML.HTMLDocument
Set idoc = i.document
Set eles6 = idoc.getElementsByTagName("a")
For Each ele6 In eles6
If ele6.href = "fileName=GeneralExtract" Then
ele6.Click
Else
End If
回答1:
Try to use the querySelector method and the [attribute^=value]
CSS selector, it will selects every element whose href attribute value begins with special value.
Sample code as below (it will select the a tag whose href attribute value begins with website/report/download.json
):
Public Sub ClickTest()
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "<the website url>"
While .Busy Or .readyState <> 4: DoEvents: Wend
ie.Document.querySelector("a[href^='website/report/download.json']").Click
End With
End Sub
Besides, you could also find the tag use the getelementsbytagname method, then using for statement to loop through the result, and according to the innerText property to find the special link. Finally, click it.
Edit
You could check the following code:
Public Sub ClickTest()
Dim ie As Object
Dim itemlist As Object 'Define a object to store the a tag list.
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "<the website url>"
While .Busy Or .readyState <> 4: DoEvents: Wend
'ie.Document.querySelector("a[href^='website/report/download.json']").Click
Set itemlist = ie.document.getElementsByTagName("a")
'Debug.Print itemlist.Length ' check the count of a tag
If Len(itemlist) > 0 Then
'using For Each statement to loopthough the a tag list.
For Each Item In itemlist
'Debug.Print Item.innerText ' check the value
'If the value is "GeneralExtract.xlsx", click the link and exit the for statement.
If Item.innerText Like "GeneralExtract.xlsx" Then
Item.Click
Exit For
End If
Next Item
End If
End With
End Sub
来源:https://stackoverflow.com/questions/59756188/clicking-on-hyperlink-with-partial-href-on-internet-explorer-using-vba