Does anyone have sample VBS code that sends a variable, waits response and repeat?
i have so far:
dim input
input = Inputbox ("Enter Var:" ,"Var sender...")
SourceURL = "http://example.com/someFunction.php?var="&input&""
that's it... my other code is not functional...
thanks in advance, hope anyone can help, totally lost in vbs... in windows in general...
Assuming that this is Windows Script Host, you can use the MSXML2 library.
do while true
Dim input, SourceURL
input = Inputbox ("Enter Var:" ,"Var sender...")
SourceURL = "http://www.google.co.uk/search?q=" & input
''// connect and send to server
Dim http: set http = CreateObject("MSXML2.XMLHTTP")
http.open "GET", SourceURL, false
http.send
if http.status = 200 then
''// do something with the return value if necessary
WScript.Echo http.responseText
else
''// problem?
end if
''// pause execution if you don't want to hit the server so often
WScript.Sleep 10
loop
if you're modifying things on the server, you should probably use a POST request instead of a GET request, but this should work if your server side script only accepts GET requests
Related
i am trying to get data using MSXML2.XMLHTTP
but it didn't work
any ideas?
Sub getdata
Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim price As String
Dim sht As Worksheet
Application.DisplayAlerts = False
Set sht = ActiveSheet
On Error Resume Next
website = "https://shopee.co.id/AFI-EC-Tshirt-Yumia-(LD-90-P-57)-i.10221730.5568491283"
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.DocumentElement.innerHTML = response
price = html.querySelector("div.AJyN7v")(0).innerText
Debug.Print price
Application.StatusBar = ""
On Error GoTo 0
Application.DisplayAlerts = True``
End Sub
I have done many ways but still not working ,
hope someone can help me
Pretty much everything on that page requires javascript to load. Javascript doesn't run with xmlhttp request to landing page so price never gets retrieved..
The price is being retrieved dynamically from an additional API call returning json.
If you examine the url you will have the following:
https://shopee.co.id/AFI-EC-Tshirt-Yumia-(LD-90-P-57)-i.10221730.5568491283
The last set of consecutive numbers is the product id i.e. 5568491283.
If you open the network tab of dev tools F12, and press F5 to refresh the web traffic that updates the page, then check on the xhr only traffic, then input your product id into the search box, the first result retrieved is the xhr which is returning the price:
https://shopee.co.id/api/v2/item/get?itemid=5568491283&shopid=10221730
The response is json so you will need a json parser to extract the result (or use regex on string - less preferable)
In the headers sub-tab you can view info about the xhr request made.
Check the terms and conditions to see if scraping allowed and also whether there is an public API for retrieving this data.
I want to write a macro on a LibreOffice spreadsheet, to send an HTTP request to an web URL and receive a JSON like response. Can i do it with LibreOffice basic macro programming? Where can i get information about the API.
I really appreciate any tips.
Thanks
I'm too late to help Antonio, but for posterity...
You can call spreadsheet functions from Basic, as explained in the open office docs. Here's a simple example that invokes the WEBSERVICE() function:
Function GetWebContent(url As string) As String
On Error GoTo ErrorHandler
Dim funtionAccess As Object
functionAccess = createUnoService("com.sun.star.sheet.FunctionAccess")
GetWebContent = functionAccess.callFunction("WEBSERVICE",Array(url))
Exit Function
ErrorHandler:
GetWebContent = "Error " & Err
End Function
Function Test
Dim url As String
url = "http://www.google.com"
Dim response As String
response = GetWebContent(url)
End Function
I'm using Excel (because the data is saved in a spreadsheet) to go through a list of a few thousand links and see if they are broken, AKA do they return a 404 or not when I RESTful GET them. However, my VBA code is returning something other than when I use curl, and in this case curl is right (the page exists). Here's my code with the link that's causing trouble (it's inside a subroutine, don't worry):
For i = StartRow To EndRow
Let copyRange = "H" & i
Let writeRange = "T" & i
query = Worksheets("Sheet1").Range(copyRange).Value
If query = "" Then
Else
With zipService
.Open "GET", query, False
End With
zipService.send
zipResult = zipService.Status
Worksheets("Sheet1").Range(writeRange).Value = zipResult
End If
Next i
The curl command line:
curl –sL –w “%{http_code} \n” http://URLHERE” –o /dev/null
The link that's causing trouble: http://www.stopwaste.org/home/index.asp#
Curl returns 200, VBA returns 404. The same link has failed several times, so I don't think it's a "server was just down for a second" situation. I thought it my have been a problem with the # character, so I removed it but got the exact same response. The code is successfully reporting other 404's, so somehow there's a situation that creates false positives (or negatives, whichever you want to call it). the "If query = "" Then" is so that there aren't GETs to empty URLS, VBA doesn't like those.
I'm pretty stumped here, and was hoping someone would be able to help me out. Thanks in advance!
Why not use .FollowHyperlink to check if the URL exists?
See this example.
Sub Sample()
Dim url As String
url = "http://www.stopwaste.org/home/index.asp#"
Debug.Print url, CheckIfURLExists(url)
url = "http://www.Google.com"
Debug.Print url, CheckIfURLExists(url)
url = "http://www.Goo00000gle.com"
Debug.Print url, CheckIfURLExists(url)
End Sub
Function CheckIfURLExists(ByVal sLink As String) As Boolean
On Error Resume Next
ThisWorkbook.FollowHyperlink (sLink)
CheckIfURLExists = Err.Number = 0
End Function
Screenshot:
Removed the '#' character and it worked just fine.
In Fiddler I saw that browser didn't send '#' character at all:
Try changing this line to include double quotes:
zipService.send ""
Also, try reseting zipService after each URL
Set zipService = Nothing
I'm assuming the excel version works for some of your URLs since your pointing out one specific one.?.?
I need a excel macro (vba) to select a file from box.com by iterating though existing folders and at the same time I need to upload the file from my machine to box.com folder using excel macro. I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
Thanks in advance.
-Edit
I am using the below code for getting authentication token. But I am getting an error message at the place of .send(url). Error message is "The server name or address could not be resolved".
Function getAuthToken()
Dim WinHttpReq As WinHttp.WinHttpRequest
Dim api_key As String
api_key = "{api_key}"
Set WinHttpReq = New WinHttp.WinHttpRequest
strUrl = "https://www.box.net/api/1.0/rest?action=get_ticket&api_key=" & api_key
WinHttpReq.Open Method:="GET", url:=strUrl, async:=False
WinHttpReq.Send
getTicket = WinHttpReq.responseText
Debug.Print getTicket
End Function
Not being a vba expert, I suspect that you'll get more answers if you tag your question with a vba tag. However, some quick scanning around shows that vba can call REST apis by doing something like this:
Dim MyURL as String
MyURL = "http://api.box.com/2.0/folders/0.xml"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
With objHTTP
.Open "GET", MyURL, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.setRequestHeader "Authorization", "BoxAuth api_key=<your api key>&auth_token=<your auth token>
.send (MyURL)
End With
I'll defer to a real VBA expert, but something roughly along these lines should work.
Yeah, this is frustrating. I tried code like Peter's using both WinHttp.WinHttpRequest.5.1 and MSXML2.ServerXMLHTTP and with both I just get a zero-length string back. No error message or anything.
I installed cURL and tested the URL. It works fine there. The script below also works fine with a generic JSON web service, like jsonplaceholder.typicode.com.
All this makes me think that Box.com is receiving the message, detecting it is coming from a non-approved source, and returning nothing . . . probably for security reasons.
Option Explicit
Const URL As String = "https://api.box.com/2.0/folders/0 -H ""Authorization: Bearer MyToken"""
'Const URL As String = "https://jsonplaceholder.typicode.com/posts/1"
Sub Test()
Dim winHTTP As Object
' Set winHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
Set winHTTP = CreateObject("MSXML2.ServerXMLHTTP")
winHTTP.Open "GET", URL
winHTTP.setRequestHeader "Content-Type", "application/json"
winHTTP.send
Debug.Print winHTTP.ResponseText
If Len(winHTTP.ResponseText) = 0 Then
MsgBox "blank string returned"
Else
Dim objResponse As Object
Set objResponse = JsonConverter.ParseJson(winHTTP.ResponseText) 'Converter from Tim Hall - https://github.com/VBA-tools/VBA-JSON
End If
End Sub
Here is vb.net 2008 code is:
Public Function CheckURL(ByVal URL As String) As Boolean
Try
Dim Response As Net.WebResponse = Nothing
Dim WebReq As Net.HttpWebRequest = Net.HttpWebRequest.Create(URL)
Response = WebReq.GetResponse
Response.Close()
Return True
Catch ex As Exception
End Try
End Function
when a url is processing in checking it hangs my application for a while. Is this possible it checks smoothly all url list without hanging my application..
Is there any other fastest way to check urls?
Note: I have about 800 urls in file to check all links a valid by website responce or not.
If an exception occurs, the WebResponse object isn't properly disposed of. This can lead to your app running out of connections. Something like this will work better:
Try
Dim WebReq As Net.HttpWebRequest = Net.HttpWebRequest.Create(URL)
Using Response = WebReq.GetResponse()
Return True
End Using
Catch ex as WebException
Return False
End Try
This using the Using keyword ensures that the response is closed and finalized whenever that block exits.
If it's the server itself that's taking awhile to respond, look into the BeginGetResponse method on the HttpWebRequest. Check MSDN for a sample on how to use it. But be warned, that way also lies madness if you are not careful.
The answer is two fold:
Most of the waiting time is due to downloading content you don't need. If you request to only return the header, you will receive substantially less data, which will make your process faster.
As Matt identified, you aren't disposing of your connections, which may slow your process.
Expanding on Matt's answer, do the following:
Try
Dim WebReq As Net.HttpWebRequest = Net.HttpWebRequest.Create(URL)
WebReq.Method = "HEAD" 'This is the important line.
Using Response = WebReq.GetResponse()
Return True
End Using
Catch ex as WebException
Return False
End Try
GetResponse delivers you the whole content to your request. If this is what you want, there's not many room to speed up the request on the client side, since it mostly depends on the URLs server how fast to reply and how much data will be send over. If you just want to check if the URL is valid (or responding at all), it might be better to just ping it.
Keep in mind GetResponse isn't disposed when it runs into an error, so use the code posted by Matt to avoid this.
For your other problem, hanging application, you might avoid this be running this code as a thread.
This works basically like this (from here):
rem at the top of the code
Imports System.Threading
...
rem your event handler, p.e. button click or whatever
trd = New Thread(AddressOf ThreadTask)
trd.IsBackground = True
trd.Start()
rem your code
Private Sub ThreadTask()
dim i as long
Do
i += 1
Thread.Sleep(100)
Loop
End Sub