I have been trying to extract data from a alt="" string, but I keep getting it wrong.
The website is: https://www.morningstar.pt/pt/funds/snapshot/snapshot.aspx?id=F00000ZK96&tab=2
and the data is the morningstar rating, which currently is 2 (and I want it to refresh automatically). The problem is that this is not expressed as text but as an image. The lines are:
td >
img src="https://www.morningstar.pt/includes/images/2stars.gif" alt="2 star">
I want to extract the "2 star", but have failed for hours with a lot of different approaches... My code is currently as following (still incomplete):
Sub Get_Web_Data()
Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim rating As Variant
website = "https://www.morningstar.pt/pt/funds/snapshot/snapshot.aspx?id=F00000ZK96&tab=2"
Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", website, False
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
request.send
response = StrConv(request.responseBody, vbUnicode)
html.body.innerHTML = response
rating = html.getElementsByClassName("value text") --------> Incomplete
Range("A1").Value = rating
End Sub
Do you have any ideas as to what I'm doing wrong? Thank you in advance.
CodePudding user response:
Try the following approach to fetch the required rating from that webpage:
Option Explicit
Sub GetData()
Const website = "https://www.morningstar.pt/pt/funds/snapshot/snapshot.aspx?id=F00000ZK96&tab=2"
Dim oHttp As Object, Html As HTMLDocument, rating As String
Set oHttp = CreateObject("MSXML2.XMLHTTP")
Set Html = New HTMLDocument
With oHttp
.Open "GET", website, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
.send
Html.body.innerHTML = .responseText
rating = Html.getElementsByClassName("starsImg")(0).alt
ThisWorkbook.Worksheets("Sheet1").Range("A1") = rating
End With
End Sub
