Extract img ALT attribute from a link - html

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 class="value text">
img class="starsImg" 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.

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

Related

Using Excel VBA, how to pull "a value from the HTML body" as well as "a cookie value" from a HTML response?

I want to extract the following items from a single website response to an Excel sheet:
Value of one of the cookies.
A value of an ID from the body of the response.
Cookie value to capture:
ID value to capture from HTML body:
I have searched for the solution, but I can find a way to pull a cookie separately with a different code and the id value separately from the HTML response body through another code.
However, combining the codes doesn't work as I need to use the same cookie value and the id value from the response in the subsequent post request.
To make the flow easier to understand, I will summarise my expectation below:
Visit "Site 1" grab the "Cookie" value and unique "ID" value from the response.
Pass the two values received in the previous response to the request of "Site 2".
Grab the link from the response of "Site 2" and visit "Site 3".
The code I have used to receive cookie values and HTML body content, which throws an error if uncommenting the codes to pull HTML body content. Kindly let me know where I am making a mistake or try a new way. (I have tried different way around, so I have kept them as comments.)
Sub Cookie_and_HTMLbody()
Dim strCookie As Variant
Dim strToken As Variant
Dim Doc As Object
Dim pontod As Object
'Dim Elements As IHTMLElementCollection
'Dim Element As IHTMLElement
On Error Resume Next
Set Doc = New HTMLDocument
With CreateObject("WinHttp.WinHttpRequest.5.1")
'With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://example.com", False
.setRequestHeader "Upgrade-Insecure-Requests", "1"
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36"
.setRequestHeader "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
.setRequestHeader "Sec-Fetch-Site", "none"
.setRequestHeader "Sec-Fetch-Mode", "navigate"
.setRequestHeader "Sec-Fetch-User", "?1"
.setRequestHeader "Sec-Fetch-Dest", "document"
.setRequestHeader "Accept-Encoding", "gzip, deflate"
.setRequestHeader "Accept-Language", "en-US,en;q=0.9"
.setRequestHeader "Connection", "close"
.send
Doc.body.innerHTML = .responseText
Set pontod = Doc.getElementById("trialrequestlanding").getElementsByTagName("div")(1).getElementsByTagName("div")(1).getElementsByTagName("div")(1).getElementsByTagName("div")(1).getElementsByTagName("form")(1).getElementsByTagName("div")(1).getElementsByTagName("input")(1)
strCookie = .getAllResponseHeaders
'strCookie = .getResponseHeader("Set-Cookie:")
'strCookie = Split(strCookie, "Set-Cookie:")
'strCookie = Trim(strCookie(UBound(strCookie)))
strCookie = Split(strCookie, vbCrLf)
strCookie = Trim(Split(Split(strCookie(5), ";")(0), ":")(1)) & "; " & Trim(Split(Split(strCookie(6), ";")(0), ":")(1))
MsgBox strCookie
'.responseType = document
'Doc = .responseText
strToken = pontod.getAttribute("value")
'strToken = Doc.querySelector("input[name='RequestVerificationToken']").getAttribute("value")
'strToken = document.getElementsByTagName("input")
'Set Doc = ie.document
MsgBox strToken
'Set Elements = .getElementsByTagName("input")
'For Each Element In Elements
' If Element.ID = "RequestVerificationToken" Then
'Range("c2").Value = Element.innerText
' MsgBox Element.Value
' End If
'Next Element
'Set Elements = Nothing
'Doc.Quit
'Set Doc = Nothing
End With
End Sub
Another code that works for retrieving a value from the HTML body is given below.
Sub Generate_Email()
Dim Shell As Object
Dim i As Variant
Dim bie As Object
Dim ie As Object
Dim Doc As HTMLDocument
Dim Elements As IHTMLElementCollection
Dim Element As IHTMLElement
'Set ie = New InternetExplorerMedium
Set ie = CreateObject("InternetExplorer.Application")
'Set ie = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
'Set ie = New InternetExplorer
ie.Visible = False
ie.navigate "https://randomsite.com/"
Do
DoEvents
Loop Until ie.readyState = 4
'Do While ie.Busy Or ie.readyState <> 4
'DoEvents
'Loop
Set Doc = ie.document
Set Elements = Doc.getElementsByTagName("span")
For Each Element In Elements
If Element.ID = "email_ch_text" Then
Range("c2").Value = Element.innerText
End If
Next Element
Set Elements = Nothing
ie.Visible = True
ie.Quit
Set ie = Nothing
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
On Error Resume Next
For Each objItem In colItems
'msgbox objItem.name & " " & objItem.ProcessID & " " & objItem.CommandLine
If objItem.Name = "ielowutil.exe" Then objItem.Terminate
Next
For Each objItem In colItems
'msgbox objItem.name & " " & objItem.ProcessID & " " & objItem.CommandLine
If objItem.Name = "iexplore.exe" Then objItem.Terminate
Next
End Sub
How to retrieve both the values using a single code?
UPDATE (02 May 2021):
I have rewritten the code that supports extracting cookie properly but has an issue with pulling the element attribute "value", as shown in image 2.
Kindly help me to identify what mistake blocks me from extracting the element attribute in the below code.
Sub Test_Cookie_and_HTML()
Dim pontod As Object
Dim html As Object
On Error Resume Next
Set html = New HTMLDocument
With CreateObject("WinHttp.WinHttpRequest.5.1")
.Open "GET", "https://portswigger.net/burp/pro/trial", False
.setRequestHeader "Upgrade-Insecure-Requests", "1"
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36"
.setRequestHeader "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
.setRequestHeader "Sec-Fetch-Site", "none"
.setRequestHeader "Sec-Fetch-Mode", "navigate"
.setRequestHeader "Sec-Fetch-User", "?1"
.setRequestHeader "Sec-Fetch-Dest", "document"
.setRequestHeader "Accept-Encoding", "gzip, deflate"
.setRequestHeader "Accept-Language", "en-US,en;q=0.9"
.setRequestHeader "Connection", "close"
.send
html.body.innerHTML = .responseText
Dim strCookie As String
Dim sessionidCookie As String
strCookie = .getResponseHeader("Set-Cookie") ' --> "SESSIONID=40DD2DFCAF24A2D64544F55194FCE04E;path=/pamsservices;HttpOnly"
sessionidCookie = GetsessionIdCookie(strCookie) ' Strips to "SESSIONID=40DD2DFCAF24A2D64544F55194FCE04E"
MsgBox sessionidCookie
MsgBox RequestVerificationToken
End With
Set pontod = html.getElementById("trialrequestlanding").getElementsByTagName("input")(1)
MsgBox pontod.getAttribute("value")
End Sub

Can't parse a certain field which is within JSON from a webpage using VBA

I'm trying to parse property information from this link which produces a JSON response. I've used here JSON and VBA converter. However, when I run the script below, I get an error keyNotFoundError. I'm trying to parse the value of properties which is within features.
Public Sub parseJson()
Dim jsonObject As Object, oElem As Variant
Dim resp$, Url$, R&
Url = "https://torontolife.com/wp-content/themes/sjm-underscores/inc/neighbourhoods/2015/compiled.json"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", Url, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36"
.send
resp = .responseText
End With
Set jsonObject = JsonConverter.parseJson(resp)
For Each oElem In jsonObject("features")
Debug.Print oElem("properties")
Next oElem
End Sub
I also get the same error when I try to like the following:
Sub Demo()
Dim Json As Object
JsonString = "[{""Entries"":[{""Name"": ""SMTH"",""Gender"": ""Male""}]}]"
JsonConverter.JsonOptions.AllowUnquotedKeys = True
Set Json = JsonConverter.ParseJson(JsonString)
Debug.Print Json(1)("Entries")
End Sub
I'm on Windows 7 (32 bit) and I'm using this library.
One more thing, they are valid JSON and I didn't encounter any error while parsing the same using Python.
Your code should be failing because oElem("properties") is a dictionary. Furthermore, within that dictionary there are a mixture of datatypes associated with the keys so you will need to test the type and handle appropriately. Or use one of the many readily available programs which will handle that and empty the entire json object for you.
Option Explicit
Public Sub ParseJson()
Dim jsonObject As Object, oElem As Variant
Dim resp$, Url$, R&
Url = "https://torontolife.com/wp-content/themes/sjm-underscores/inc/neighbourhoods/2015/compiled.json"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", Url, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36"
.send
resp = .responseText
End With
Set jsonObject = JsonConverter.ParseJson(resp)
Dim key As Variant, propertyTypes As Scripting.Dictionary
Set propertyTypes = New Scripting.Dictionary
For Each oElem In jsonObject("features")
For Each key In oElem("properties")
Debug.Print key, vbTab, TypeName(oElem("properties")(key))
propertyTypes(key) = TypeName(oElem("properties")(key))
Next
Next oElem
'Review propertyTypes dict and/or immediate window print out
Stop
End Sub

HTML Scrape is getting different number now

I built the below code to pull the price of a mutual fund into excel via VBA. It worked up until last night. It just started pulling a different number (the % return on the dow. Top of page.). I looked to see if the website layout changed, but can't figure it out.
I believe the code is getting confused between the "value" I am trying to pull and the "value positive" class for the dow.
Is there a way for the code to focus on "value" not "value positive"?
Sub ExtractLastValue()
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 800
objIE.Visible = True
objIE.Navigate ("https://www.marketwatch.com/investing/fund/lfmix")
Do
DoEvents
Loop Until objIE.readystate = 4
Dim myValue As String: myValue = objIE.document.getElementsByClassName("value")(0).innerText
Range("C3").Value = myValue
End Sub
Always declare all variables. The best way to do this is to write Option Explicit at the top of each module. The declarations also belong at the top of the macro.
First fence the desired value before you get it via the CSS class "value".
Option Explicit
Sub ExtractLastValue()
Dim objIE As Object
Dim url As String
Dim myValue As String
url = "https://www.marketwatch.com/investing/fund/lfmix"
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 800
objIE.Visible = True
objIE.navigate url
Do: DoEvents: Loop Until objIE.readyState = 4
myValue = objIE.document.getElementsByClassName("intraday__price")(0).getElementsByClassName("value")(0).innerText
Range("C3").Value = myValue
End Sub
You can scrape that value in several ways. Here is one of the faster methods. When the execution is done, you should get the value in Range("C3").
Sub FetchValue()
Const Url$ = "https://www.marketwatch.com/investing/fund/lfmix"
Dim Html As New HTMLDocument, S$, elem As Object
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", Url, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
.send
Html.body.innerHTML = .responseText
[C3] = Html.querySelector("h3.intraday__price > .value").innerText
End With
End Sub
Make sure you don't execute the script incessantly as the site is very good at banning ips temporarily.

VBA - XML Web Log-In to USGA GHIN Website - Not Working

I have tried two VBA XML methods for logging on to the USGA Website, it seems straight forward, but neither works?! To test this, you will need your own GHIN Number and Last Name. Can someone please point out how I an screwing this up?
website = "https://www.ghin.com/login"
Sub Get_GHIN_Data()
Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim price As Variant
website = "https://www.ghin.com/login"
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
'********* Method 1 ************************************
'Dim oLogin As Object, oPassword As Object
'Set oLogin = .document.getElementsByName("ghinNumber")(0)
'Set oPassword = .document.getElementsByName("lastName")(0)
'oLogin.Value = ghinNumber 'real GHIN NUMBER
'oPassword.Value = LastName 'real Last Name
'html.document.forms(0).submit
'********* Method 2 ************************************
'html.getElementById("ghinNumber").Value = "ghinNumber" 'real GHIN NUMBER
'html.getElementById("lastName").Value = "Last name" 'real Last Name
'html.getElementClassName("btn fill cardinal").Click
'html.forms(0).submit
End Sub
Did you try this way? I think it will work.
Sub GetInformation()
Const Url = "https://api2.ghin.com/api/v1/public/login.json?"
Dim Http As New XMLHTTP60, ghinNum$, lastName$
ghinNum = "" 'put your ghinNum here
lastName = "" 'put your lastName here
With Http
.Open "GET", Url & "ghinNumber=" & ghinNum & "&lastName=" & lastName & "&remember_me=false", False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
.setRequestHeader "Referer", "https://www.ghin.com/login"
.send
End With
MsgBox Http.responseText
End Sub

VBA XMLHTTP query returning 403 error

I am currently attempting to retrieve a json string using XMLHTTP in VBA from the website url detailed below. Loading the first url creates a session, which I retrieve from the HTML body. A call to the second url, using the session ID & other request headers visible from develop tools results in a 403 error. I have tried multiple combinations of headers with no effect. For deployment purposes a VBA solution is required. Any input/ideas would be much appreciated.
Sub test()
Dim wbk_TB As Workbook
Dim var_array As Variant
Dim url As String
Dim data As Variant
Dim XMLHTTP As MSXML2.XMLHTTP
Dim hdoc As MSHTML.HTMLDocument
Set wbk_TB = ThisWorkbook
Set XMLHTTP = New MSXML2.XMLHTTP
url = "http://www.eex-transparency.com/homepage/power/germany/production/availability/non-usability"
XMLHTTP.Open "GET", url, False
XMLHTTP.setRequestHeader "Accept", "application/json, text/plain, */*"
XMLHTTP.send
data = XMLHTTP.responseText
Dim HTMLdoc As MSHTML.HTMLDocument
Set HTMLdoc = New MSHTML.HTMLDocument
HTMLdoc.body.innerHTML = XMLHTTP.responseText
Name = "session=" & HTMLdoc.getElementsByName("session").Item(0).Value
url = "http://www.eex-transparency.com/dsp/tem-12?country=de&limit=50&offset=50"
XMLHTTP.Open "GET", url, True
XMLHTTP.setRequestHeader "Host", "www.eex-transparency.com"
XMLHTTP.setRequestHeader "Proxy-Connection", "keep-alive"
XMLHTTP.setRequestHeader "Accept", "application/json, text/plain, */*"
XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
XMLHTTP.setRequestHeader "Referer", "http://www.eex-transparency.com/homepage/power/germany/production/availability/non-usability"
XMLHTTP.setRequestHeader "Accept-Encoding", "gzip,deflate,sdch"
XMLHTTP.setRequestHeader "Cache-Control", "max-age=0"
XMLHTTP.setRequestHeader "Accept-Language", "en-US,en;q=0.8"
XMLHTTP.setRequestHeader "Cookie", Name
XMLHTTP.send
While XMLHTTP.readyState <> 4
DoEvents
Wend
data = XMLHTTP.responseText
End Sub
XMLHttp object does not allow unsafe header settings including spoofed referer header. Details are available in this answer
As the referer header is missing in the request, a status 403 is returned. In case you need to get the JSON from VBA, you would need to use an Internet Explorer object and browse to the first URL and once that is loaded, need to navigate to the Second URL by programatically emulating a click on the correct link and then try to capture the data.