I am trying to get data from Yahoo Finance on Excel on Mac.
As far as I know, the usual approach to get web data on Mac is WebQuery. However, sometimes it works without issues, sometimes throws an error 1004 for the same set of tickers it worked before without issue. Text of the error:
"Microsoft Excel cannot access the file %link%. There are several possible reasons:"
I have no clue why does that happen. The only suggestion is because the URL does not contain a cookie / crumb Yahoo needs.
For testing purposes, I used WinHttpRequest on Windows. It works - Excel successfully gets the data.
There's an alternative on Mac - Tim Hall's WebHelpers. I was able to get the cookie and the crumb on Mac with this great set of tools.
But when I try downloading the CSV from Yahoo the response.Content has this string: {"finance":{"result":null,"error":{"code":"Not Acceptable","description":"HTTP 406 Not Acceptable"}}}.
Generally, I have several questions:
Is there a way to add a cookie to the WebQuery approach? Still, I am not sure if that works and helps to evade the error.
Why does Response return Error 406? Particularly this code snippet:
client.BaseUrl = tickerURL
request.Method = HttpGet
request.Format = PlainText
request.AddCookie "Cookie", cookie
request.AddHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
Set response = client.Execute(request)
resultFromYahoo = response.Content
Here's a code to receive Yahoo Finance data using either WinHttpRequest on Windows or Tim Hall's package on Mac:
Sub getYahooFinanceData(stockTicker As String, StartDate As String, EndDate As String, frequency As String, cookie As String, crumb As String)
' forked from:
' http://investexcel.net/multiple-stock-quote-downloader-for-excel/
Dim resultFromYahoo As String
Dim objRequest
Dim csv_rows() As String
Dim tickerURL As String
'Make URL
tickerURL = "https://query1.finance.yahoo.com/v7/finance/download/" & stockTicker & _
"?period1=" & StartDate & _
"&period2=" & EndDate & _
"&interval=" & frequency & "&events=history" & "&crumb=" & crumb
'***************************************************
'Get data from Yahoo
#If Mac Then
Dim client As New WebClient
Dim response As WebResponse
Dim request As New WebRequest
client.BaseUrl = tickerURL
request.Method = HttpGet
request.Format = PlainText
request.AddCookie "Cookie", cookie
request.AddHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
Set response = client.Execute(request)
DoEvents
'' ERROR 406 on MAC ''
If response.StatusCode = Ok Then
resultFromYahoo = response.Content
Else
MsgBox "An error occured while getting data for " & stockTicker & "'", vbInformation
Exit Sub
End If
#Else
Set objRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
With objRequest
.Open "GET", tickerURL, False
.SetRequestHeader "Cookie", cookie
.Send
.WaitForResponse
resultFromYahoo = .ResponseText
End With
#End If
'***************************************************
csv_rows() = Split(resultFromYahoo, Chr(10))
End Sub
Finally came to a solution! Found the answer in similar topic related to Python: https://stackoverflow.com/a/68259438/8524164
In short, we need to modify user-agent and other request parameters to emulate a real browser. Instead of this one line:
request.AddHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
We need to add 5 lines:
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
request.AddHeader "Accept-Language", "en-US,en;q=0.5"
request.AddHeader "DNT", "1"
request.AddHeader "Connection", "close"
The final sub:
Sub getYahooFinanceData(stockTicker As String, StartDate As String, EndDate As String, frequency As String, cookie As String, crumb As String)
' forked from:
' http://investexcel.net/multiple-stock-quote-downloader-for-excel/
Dim resultFromYahoo As String
Dim objRequest
Dim csv_rows() As String
Dim tickerURL As String
'Make URL
tickerURL = "https://query1.finance.yahoo.com/v7/finance/download/" & stockTicker & _
"?period1=" & StartDate & _
"&period2=" & EndDate & _
"&interval=" & frequency & "&events=history" & "&crumb=" & crumb
'***************************************************
'Get data from Yahoo
#If Mac Then
Dim client As New WebClient
Dim response As WebResponse
Dim request As New WebRequest
client.BaseUrl = tickerURL
request.Method = HttpGet
request.Format = PlainText
request.AddCookie "Cookie", cookie
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
request.AddHeader "Accept-Language", "en-US,en;q=0.5"
request.AddHeader "DNT", "1"
request.AddHeader "Connection", "close"
Set response = client.Execute(request)
DoEvents
If response.StatusCode = Ok Then
resultFromYahoo = response.Content
Else
MsgBox "An error occured while getting data for '" & stockTicker & "'", vbInformation
Exit Sub
End If
#Else
Set objRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
With objRequest
.Open "GET", tickerURL, False
.SetRequestHeader "Cookie", cookie
.Send
.WaitForResponse
resultFromYahoo = .ResponseText
End With
#End If
'***************************************************
csv_rows() = Split(resultFromYahoo, Chr(10))
End Sub
Related
I am beginner at VBA. I have done the below code by referring to lot of articles found online.
I am trying to fetch API data from a website. It is taking the first fetch and I need the data to be fetched every 5 mins. But it is not refreshing at all. What can I do? Can anyone have a look at the code and advise?
I am using the below code to get the JSON data and later I am extracting using a JSON parser.
Sub FetchOptionChain()
Dim Json As Object
Dim webURL, webURL2 As String, mainString, subString
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim dtArr() As String
Dim request, request2 As Object
Dim HTML_Content As Object
Dim requestString As String
webURL2 = "https://www.nseindia.com/"
webURL = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"
subString = "Resource not found"
Set HTML_Content = CreateObject("htmlfile")
'Get the WebPage Content to HTMLFile Object
With CreateObject("msxml2.xmlhttp")
.Open "GET", webURL2, False
.send
End With
FetchAgain:
With CreateObject("msxml2.xmlhttp")
.Open "GET", webURL, False
'Found online that I have to add the below to remove the cached results. Adding this is hanging the excel and it never comes out of it. Excel is hanging here
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
.send
mainString = .ResponseText
If InStr(mainString, subString) <> 0 Then
' Data has not been fetched properly. Will wait two seconds and try again.
Application.Wait (Now + TimeValue("0:00:2"))
GoTo FetchAgain
Added end with, end if and end sub. And fixed indenting to make code easier to read.
Sub FetchOptionChain()
Dim Json As Object
Dim webURL, webURL2 As String, mainString, subString
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim dtArr() As String
Dim request, request2 As Object
Dim HTML_Content As Object
Dim requestString As String
webURL2 = "https://www.nseindia.com/"
webURL = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"
subString = "Resource not found"
'''''''''''''''''''''''''''''''''''''''''''''
''' I don't understand this part though '''
'''''''''''''''''''''''''''''''''''''''''''''
Set HTML_Content = CreateObject("htmlfile")
'Get the WebPage Content to HTMLFile Object
With CreateObject("msxml2.xmlhttp")
.Open "GET", webURL2, False
.send
End With
'''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''' To here ''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''
FetchAgain:
With CreateObject("msxml2.xmlhttp")
.Open "GET", webURL, False
'Found online that I have to add the below to remove the cached results. Adding this is hanging the excel and it never comes out of it. Excel is hanging here
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
.send
mainString = .responseText
End With
If InStr(mainString, subString) <> 0 Then
' Data has not been fetched properly. Will wait two seconds and try again.
Application.Wait (Now + TimeValue("00:00:02"))
GoTo FetchAgain
End If
End Sub
But it runs and works as expected for me.
I'm trying to access https://www.nseindia.com/ to get the cookies in response headers.
But using MSXML2.XMLHTTP returns the cookie value as empty string.
From, VBA Microsoft.XMLHTTP setRequestHeader not sending cookie - I tried using WinHTTP, which did not connect at all and kept timing out. Apparently that can only be used on HTTP requests. How can the same be done for a HTTPS request?
MSXML2.ServerXMLHTTP also does not seem to support HTTPS requests.
Please find the code snippets I used for the 2 methods below:
MSXML2.XMLHTTP
Sub Get_Web_Data()
Dim request As Object
Dim response As String
Dim website As String
' Website to go to.
website = "https://www.nseindia.com/"
' Create the object that will make the webpage request.
Set request = CreateObject("MSXML2.XMLHTTP")
' Where to go and how to go there.
request.Open "GET", website, False
' Set headers.
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
request.setRequestHeader "user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"
request.setRequestHeader "accept-Encoding", "gzip , deflate"
request.setRequestHeader "accept-language", "en-US,en;q=0.9"
request.setRequestHeader "Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
request.setRequestHeader "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
' Send the request for the webpage.
request.send
responseHeaders = request.getAllResponseHeaders
MsgBox responseHeaders
End Sub
winHTTP
Sub Get_Web_Data_Cookie()
Dim website As String
Dim cookieString As String
Dim XMLHTTP As WinHttp.WinHttpRequest
' Website to go to.
website = "https://www.nseindia.com/"
'Initialize XMLHttp Object
Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") ' needs Microsoft WinHTTP Services 5.1 reference
' XMLHTTP.Option(WinHttpRequestOption_EnableRedirects) = False ' WinHttpRequestOption_EnableRedirects=6
XMLHTTP.Open "GET", website, False
' Set headers.
XMLHTTP.setRequestHeader "user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"
XMLHTTP.setRequestHeader "accept-encoding", "gzip , deflate"
XMLHTTP.setRequestHeader "accept-language", "en-US,en;q=0.9"
' Send the request for the webpage.
XMLHTTP.send
responseHeaders = XMLHTTP.getAllResponseHeaders
MsgBox responseHeaders
End Sub
Okay, I have finally solved it using the same steps as mentioned in - How to get cookie information using excel vba
This was NOT a Certificate issue at all.
Here is my code.
Public Function NSEDataCall(website, setCookies) As String
Dim XMLHTTP As WinHttp.WinHttpRequest
'Initialize XMLHttp Object
'Use the best/proper XMLHttp object available on your system
Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") ' needs Microsoft WinHTTP Services 5.1 reference
' XMLHTTP.Option(WinHttpRequestOption_EnableRedirects) = False ' WinHttpRequestOption_EnableRedirects=6
XMLHTTP.Open "GET", website, False
' Set headers.
XMLHTTP.setRequestHeader "REFERER", website
XMLHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
XMLHTTP.setRequestHeader "Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
XMLHTTP.setRequestHeader "Accept-Language", "en-us,en;q=0.5"
XMLHTTP.setRequestHeader "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
' Set cookie value - used for second call
If Len(setCookies) > 0 Then
XMLHTTP.setRequestHeader "cookie", setCookies
Else
End If
XMLHTTP.send
If Len(setCookies) > 0 Then
' Get response headers
response = XMLHTTP.getAllResponseHeaders
' Debug.Print response
' Split by new line
responseArray = Split(response, vbCrLf)
' Debug.Print responseArray(7)
' Helps to identify dataType - output comes as code numbers
' MsgBox (VarType(Trim(Split(Split(responseArray(5), ";")(0), ":")(1)) & "; " & Trim(Split(Split(responseArray(6), ";")(0), ":")(1))
' Return the sv_bm cookie in response array from indices 7 (indices start from 0)
NSEDataCall = setCookies & "; " & Trim(Split(Split(responseArray(7), ";")(0), ":")(1))
Else
' Get response headers
response = XMLHTTP.getAllResponseHeaders
' Debug.Print response
' Split by new line
responseArray = Split(response, vbCrLf)
' Helps to identify dataType - output comes as code numbers
' MsgBox (VarType(Trim(Split(Split(responseArray(5), ";")(0), ":")(1)) & "; " & Trim(Split(Split(responseArray(6), ";")(0), ":")(1))
' Return the cookies in response array from indices 5 to 9
NSEDataCall = Trim(Split(Split(responseArray(5), ";")(0), ":")(1)) & "; " & Trim(Split(Split(responseArray(6), ";")(0), ":")(1)) & "; " & Trim(Split(Split(responseArray(7), ";")(0), ":")(1)) & "; " & Trim(Split(Split(responseArray(8), ";")(0), ":")(1)) & "; " & Trim(Split(Split(responseArray(9), ";")(0), ":")(1))
'Debug.Print (responseArray(5) + responseArray(6))
End If
End Function
Sub GetNSECookies()
Dim website As String
Dim cookieValues As String
Dim website2 As String
Dim cookieValuesFinal As String
' First call
website = "https://www.nseindia.com/market-data/securities-lending-and-borrowing"
cookieValues = NSEDataCall(website, cookieValues)
' Debug.Print (cookieValues)
' Second call for sv_bm cookie
website = "https://www.nseindia.com/market-data/securities-lending-and-borrowing"
cookieValues = NSEDataCall(website, cookieValues)
Debug.Print (cookieValues)
End Sub
the output for this code snippet is as below.
nsit=p8XRMHoQSM5uEQUM7XIJdT8B; nseappid=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhcGkubnNlIiwiYXVkIjoiYXBpLm5zZSIsImlhdCI6MTYxNjA0MDYwNCwiZXhwIjoxNjE2MDQ0MjA0fQ.BLTcAzB76DYfZI3rXUl2PkrpgUZp9w8r1UF-yXGo4Os; AKA_A2=A; ak_bmsc=520CE4F35658A3B15048CCCE60A4E7547D38DE9EEC3000009CD25260A2FB3E43~pl9bruXUs5nNKxK5S/bJRyN580uFS9ZtV8nwBP8Qm3XWDms7ASCi3ptfGjv0tdgor2Su0pgG13S0ZfheirbKwG8ckZjIrwFJekieseYkMEljA7MivwOo+izySca+cktj38v8dtutTScCfjVJGZOpaCwWBzr9v3JYpKVjdQCqnb4KB7v51O1ZmuqCtoK4b2sA0qQUytHgGGgXf8ZtFFv0VT7AjbZNKcjEdm4LTLidgmXX0=; bm_mi=C5AE845425DB55CAB9626B7A4DD0F7FD~D8U6FxMuj0HFHRdsgmxmpC2LOBFGEpHQgTAoFX8vOTeoNfTZ/KMz4NOdu52Ao8qbord9vfGA+KQ2/HN+8ILK5BSLxT//yRFIsPKmHCiA7bxUU14SqZO3gQo4BVW92dqJodsoqYpEXwXEjOtbDCZ1E2w9aERcEpCAQeLuQvzlAjiJwmIia0iAAuTc2eewlyBtb0oSaRCMTZXDcuvziSCCfzdo8N8lTtWaMICsVClYXQqaIeqGWFjh1xyKo+jj1cJxYULE3vXWBSYaRHnJLZX/+oyYWrkqvrwPn+/PDpN1iPY=; bm_sv=E2881456097AB72A45E379FB86952E6F~iCyF/Esh3Bj9L205JScGaCUgr9qyeITu91BXox9pKZCvOvYx6Rt5m2VTyNCSMmYIBqZkRD0R3n11Htgb0Ill5TX9TXgVk+kL++6CUS9o93j
LGwFnXVBbQ60xz0+iuscdi7T93Dlv7JL9Lw32gobE/R6NmwzDjaxT2WFmKf7nV/M=
Adapting the solution found here:
This works for me with url of https://www.stackoverflow.com:
Sub test()
Dim url As String
url = "https://www.stackoverflow.com"
Dim winHttpReq As Object
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
'Ignoriere SSL-Errors
winHttpReq.Option(4) = &H3300
winHttpReq.Open "GET", url, False
winHttpReq.Send ("")
Debug.Print winHttpReq.getAllResponseHeaders
End Sub
Outputs:
Cache-Control: private
Connection: keep-alive
Date: Wed, 17 Mar 2021 04:32:59 GMT
Transfer-Encoding: chunked
Via: 1.1 varnish
Content-Type: text/html; charset=utf-8
Accept-Ranges: bytes
Server: Microsoft-IIS/10.0
Vary: Fastly-SSL
strict-transport-security: max-age=15552000
x-route-name: Home/Index
x-frame-options: SAMEORIGIN
x-flags: AA
x-aspnet-duration-ms: 3
x-request-guid: 4e8b7ffc-6609-4009-b59e-f1d72d598284
x-is-crawler: 0
x-providence-cookie: f34f05db-5db7-2f34-bb41-7c9c32fada8c
feature-policy: microphone 'none'; speaker 'none'
content-security-policy: upgrade-insecure-requests; frame-ancestors 'self' https://stackexchange.com
x-page-view: 1
X-Served-By: cache-syd10151-SYD
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1615955579.318915,VS0,VE282
X-DNS-Prefetch-Control: off
But for https://www.nseindia.com it just times out. Perhaps you can update this method with the request headers which may prevent the timeout.
I'm trying to parse the text within yellow colored area from a website which is visible when you fill in the inputbox next to parcel id and hit the search button. Here is an example parcel id 01-01-350000 for your test.
I've created a macro using xmlhttp requests to scrape the very content. It seems I've done everything in the right way but for some reason the macro is not working. It is still in the landing page even after making a post requests.
I've tried with:
Sub GetStatus()
Const Url$ = "https://obftax.baltimorecountymd.gov/(S(m15cp5mubgqql1yzzjrxez45))/Default.aspx"
Dim Html As New HTMLDocument
Dim elem As Object, sVal$, payload As Variant
sVal = "01-01-350000"
payload = "RetryCounter=0&Action=MainMenu&ParcelType=RE&ParcelID=" & sVal & "&ParcelAddress=&PageNumber=1&SearchType=ParcelID&SearchParcel=" & sVal & "&SearchTaxNumber=&SearchStreetNumber=&SearchStreetName="
With CreateObject("MSXML2.XMLHTTP")
.Open "POST", Url, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.Send payload
Html.body.innerHTML = .responseText
End With
Set elem = Html.querySelector("#tvrMessage")
If Not elem Is Nothing Then
MsgBox elem.innerText
Else:
MsgBox "failed to parse"
End If
End Sub
How can I scrape the text from the yellow colored area using vba making use of xmlhttp requests?
I'm trying to scrape a website developed with ASP.NET Ajax with Excel VBA. I'm using the Microsoft HTML Object Library and the Microsoft XML, v6.0 library. What I would like to do is to get in a table all the items in the second text box when I select an item in the first text box.
When you select an item in the first text box automatically the items on the second text box are loaded. So first I make a GET request to the website, then I scrape all the elements with the class aspNetHidden. I add two elements to the POST string that doesnt' appear in the first scrape: ctl00$ctl18, __ASYNCPOST, with their respective values. I also added the value for the first text box ctl00$MainContent$cboDenominacionSocial.
Sub Macro1()
'
' Macro1 Macro
'
' Declare variables
Dim xmlhttp As New MSXML2.XMLHTTP60
Dim urlMF As String
'
urlMF = "https://www.smv.gob.pe/Frm_EVCP?data=5A959494701B26421F184C081CACF55BFA328E8EBC"
'
'
xmlhttp.Open "GET", urlMF, False
'xmlhttp.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3842.0 Safari/537.36"
'xmlhttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
xmlhttp.send
Dim bodySMV As New HTMLDocument
bodySMV.body.innerHTML = xmlhttp.responseText
Dim topicsSMV As Object
Dim topicElem As Object
Set topicsSMV = bodySMV.getElementsByClassName("aspNetHidden")
Dim postReq As String
postReq = ""
i = 1
For Each topic In topicsSMV
Set topicElem = topic.getElementsByTagName("input")
For Each dataTopic In topicElem
Cells(i, 1) = dataTopic.Name
Cells(i, 2) = dataTopic.Value
temp = dataTopic.Name & "=" & dataTopic.Value
If i = 1 Then postReq = "ctl00%24ctl18=ctl00%24MainContent%24UpdatePanel1%7Cctl00%24MainContent%24cboDenominacionSocial"
If i > 1 Then postReq = postReq & Chr(38) & temp
i = i + 1
Next dataTopic
Next topic
postReq = postReq & "ctl00%24MainContent%24cboDenominacionSocial=156429&__ASYNCPOST=true&"
Cells(i, 1).Value = postReq
xmlhttp.Open "POST", urlMF, False
xmlhttp.send postReq
bodySMV.body.innerHTML = xmlhttp.responseText
'
End Sub
I'd like to get all the list of possible elements from the second text box, depending on the selection of the first box. What am I missing in my POST request?
When executing this code it is filling the required text box on the website but pressing the find button gives the output 'not found' in the message box.
Subsequently, if i manually just click in the text box on the filled value and then click the find button, it shows the desired result.
How can I make this work?
Public Sub experiment()
Dim ie As InternetExplorer
Set ie = New InternetExplorer
ie.navigate "https://www.latlong.net/"
Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE
Dim doc As HTMLDocument
Set doc = ie.document
Dim inputElement As HTMLInputElement
Set inputElement = doc.getElementsByClassName("width70")(0)
inputElement.Value = "Delhi Airport, India"
ie.Visible = True
doc.getElementById("btnfind").Click
Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE
End Sub
Rather than IE automation and interacting with the page as a user would, the code below should emulate the request triggered by the 'Find' button on the page, but you need to assign a value to placeName in the code (currently it is "Delhi Airport, India").
If you are interested in only the co-ordinates (and no other information on the rest of the page), then this approach might be okay for you.
You'll need to add a reference (Tools > References > Scroll down and tick Microsoft XML, v6.0 > OK) before trying to run the code.
Option Explicit
Private Sub Experiment()
Dim placeName As String
placeName = "Delhi Airport, India"
Dim WebClient As MSXML2.ServerXMLHTTP60
Set WebClient = New MSXML2.ServerXMLHTTP60
With WebClient
.Open "POST", "https://www.latlong.net/_spm4.php", True
.setRequestHeader ":authority", "www.latlong.net"
.setRequestHeader ":method", "POST"
.setRequestHeader ":path", "/_spm4.php"
.setRequestHeader ":scheme", "https"
.setRequestHeader "accept", "*/*"
.setRequestHeader "content-type", "application/x-www-form-urlencoded"
.setRequestHeader "origin", "https://www.latlong.net"
.setRequestHeader "referer", "https://www.latlong.net/"
.setRequestHeader "user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"
.setRequestHeader "x-requested-with", "XMLHttpRequest"
Dim bodyToSend As String
bodyToSend = "c1=" & Application.EncodeURL(placeName) & "&action=gpcm&cp="
.send bodyToSend
.waitForResponse
MsgBox ("Server's response to the request for Place Name '" & placeName & "' is " & _
vbNewLine & vbNewLine & .responseText)
End With
End Sub
You can access the server's response (which will contain the co-ordinates if the request was successful) with WebClient.responseText (or just .responseText inside the With statement) -- and then do what you need to with it.