So I understand how to pull data from a single weblink looking at tables. I cannot find not 1 tutorial anywhere on the web about how to do so getting it from Div elements and no one talks about it at all. Can someone please give me an example or something? Either Excel or Google Spreadsheets.
Im trying to teach myself doing so but using this website https://newworldstatus.com/regions/us-east for a small project I want to do.
Thank you in advance.
This is not a comprehensive answer, just intended to show you how some very basic concepts work. Second, an answer for Sheets, but let me preface all of this by saying that while your test URL seems simple enough, you will not be able to do any of this for that specific URL. They are either actively trying to stop scraping or they just have it set up in a way that makes it difficult to scrape by accident. If you directly make a web request to that URL, you will get back the JS code that actually handles the data load-in and not the data itself, so any kind of parsing you try to do will fail because what you see in the page isn't what is actually coming back on the initial page request. All the html that will be in the page is enough to show this:
You would need to either try to read through the code and figure out what they're doing, or do some tinkering in the javascript console, and probably some fairly high-level tinkering. So for a first project, or just to learn some basics, I think I would pick a different test case.
First, in VBA. It's both complicated and not all that complicated at the same time. If you know how web technologies work non-language specifically, then it all works pretty much the same way in VBA. First, you'll need to make a web request. You can do that with the winHTTP library or the msXML library. I usually use winHTTP, but unless what you're doing is complex, either one is fine.
WEB REQUEST:
You'll need to instantiate a request object. You can do that by either adding a reference to the library (tools->references-> and pick the library out of the list) or you can use late binding. I prefer to add the reference, because you get intellisense that way. Here are both:
Dim req As New WinHttp.WinHttpRequest
or
Set req = CreateObject("WinHttp.WinHttpRequest.5.1")
Then you open the request. I'm going to assume this is a straight GET. POST requests get a little more complicated:
req.Open "GET", url, TRUE
If you have the reference added and created the req with Dim, then you'll get the intellisense and as you type that the arguments will pop up and you can use that to refer to the documentation if you have questions. TRUE here is to send it asynchronously, which I would do. If you don't, it will block up the interface. This the Open method, which you can find in the documentation.
https://learn.microsoft.com/en-us/windows/win32/winhttp/iwinhttprequest-interface
Then use
req.send
req.WaitForResponse
source = req.responseText
to send the request. WaitForResponse is needed only if you send the request asynchronously. The last part is to get the responseText into a variable.
PARSING:
Then you'll need to do some stuff with the MSHTML library, so add a reference to that. You can also late bind, but I would not, because it will be very helpful to you to have the prompts in intellisense.
First, set up a document
https://learn.microsoft.com/en-us/dotnet/api/mshtml.htmldocument?view=powershellsdk-1.1.0
and write the source you just fetched to it:
Dim doc as new MSHTML.HTMLdocument
doc.write source
Now you have a document object you can manipulate. The trick is to get a reference to the element you want. There are two methods that will return an element:
getElementById
querySelector
If you are lucky, the element you are looking for will have a unique ID and you can just get it. If not so lucky, you can use a selector that identifies it uniquely. In either case, you will set up an IHTMLElement to return to:
Dim el as MSHTML.IHTMLElement
set el = doc.getElementById("uniqueID") 'whatever the unique ID is
Once you have that, you can use the methods and properties of the element to return information about it:
https://learn.microsoft.com/en-us/dotnet/api/mshtml.ihtmlelement?view=powershellsdk-1.1.0
There are more specific interfaces, like
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
You can use the generic IHTMLElement, but sometimes there are advantages to using a specific element type, for instance, the properties that are available to it.
Sometimes you will have to set up an IHTMLElementCollection:
https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa703928(v=vs.85)
and iterate it to find the specific element you are looking for. There are four methods that return collections:
getElementsByName
getElementsByTagName
getElementsByClassName
querySelectorAll
getElementsByClassName is sometimes problematic, so forewarned is forearmed.
If you need to do that, set up and IHTMLElementCollection and return the list to that:
dim els as MSHTML.IHTMLElementCollection
set els = doc.getElementsByTagName("tagName") 'for instance a for anchors, div for divs
That is about it. There is obviously more to it, but a comprehensive answer would be very long. This is mostly intended to point you in the right direction and give you more stuff to google.
I will say that you should test out some of these methods in the browser first. They exist in many languages, and all major browsers have developer tools. For Chrome, for instance, press Ctrl+Shift+I to bring up the dev tools, and then in the console window type something like:
document.getElementById("uniqueID")
and you should get the node. or
document.getElementsByClassName(".test") 'where test is the name of the class
document.querySelectorAll("div") ' where you pass a valid CSS selector
and you will get the node list.
It will be quicker to experiment there than to try to set it up and debug in VBA. once you have a good handle on how it works, try to transfer that knowledge to a VBA implementation.
Here is a basic overview of .querySelector to get you started on understanding how those work, although they can get very complicated. In fact, querySelector is my go to method for finding elements.
https://www.w3schools.com/jsref/met_document_queryselector.asp
Now, Google Sheets:
You don't really want to use IMPORTHTML, even though it seems counterintuitive. That function (AFAIK) only supports tables and lists, and it's index based, too, which means you give it a number n and it returns the nth table or list in the page. That means that if they ever change the layout, or the layouts are dynamic in any way, then you won't be able to rely and an index to accurately identify what you want. Also, as you noted people don't really use tables much anymore, and when they say list I'm pretty sure they mean on and elements, which is also not going to be that useful to you. Here's the docs:
https://support.google.com/docs/table/25273?hl=en&visit_id=637732757707317357-1855795725&rd=2
But you can use IMPORTXML. Even though it says XML, you can still use it to parse HTML (for reasons and with limitations that are out of scope for this answer). IMPORTXML takes a URL and an xpath selector. In this way it's similar to the document.querySelector and querySelectorAll methods. Here is some information on xpath in tutorial from from w3schools.
https://www.w3schools.com/xml/xpath_intro.asp
And if you want to test selectors in Chrome you can use $x("selector") in the javascript console in the dev tools. I believe Firefox also supports this, but I am not sure if other browsers do. If not, you can use document.evaluate:
https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
Even though you can't actually use this in sheets against the URL you've given, let's take a look at a couple of xpath selectors in that context. Hit Ctrl+Shift+I to bring up the dev tools (hopefully you are using Chrome), and then go to the elements tab. If you don't have the javascript console showing in the bottom pane, hit Esc. You should see something like this:
Use the arrow icon in the top left of the dev tools to search the elements, and just click on the first row in the table:
so that you can see the structure of the elements, and figure out how to parse out what you want from it. You'll notice that the cell that's highlighted is contained in a div with a role of "row" and an attribute of row-id. I think that's where I would start. So an xpath to that container would look something like this:
//div[#row-id=1]
where we are fetching all elements (//) that match div and have an attribute (#) of row-id = 1.
If you want to get the children of that container, you just add another level to the path
//div[#row-id=1]/div
where we want to get all children (/) that are divs.
And I notice that they all have a col-id attribute, so if you wanted to fetch the "set" information you'd just specify divs that have an attribute of col-id = 'set':
//div[#row-id=1]/div[#col-id='set']
and to get the text out of that:
//div[#row-id=1]/div[#col-id='set']/text()[1]
since it looks like the second node is the one that has the team name in it. Again, you can see how this WOULD work in the dev tools, but you won't actually be able to use this for your URL.
I'm not going to spend a lot of time here. As already stated, you won't be able to use this method on your specific URL. If you can figure out the actual URL that your URL wraps around, then perhaps. Also, since there's only one argument, the selector, then there's not much more to expound on. If you needed something more complex, like the ability to iterate over a set of matching nodes, you could probably do it in Scripts, but I would probably just switch to Excel if it started getting that complicated. The only exception would be if the data was JSON formatted, in which case Scripts will be able to handle that better than VBA, although I would probably switch to a different language entirely in that case.
Since your URL is probably not good for testing, I'm going to point you to this tutorial from Geckoboard, which has a few different examples from sites like Wikipedia and Pinterest.
https://www.geckoboard.com/blog/use-google-sheets-importxml-function-to-display-data/
So google around, experiment, and let me know if you need any help. And this was all off the top of my head, so let me know if any of this stuff throws errors so I can edit the answer.
Also, be aware that Excel is not always the right tool for dealing with this. Very often, while the page might have the elements you are looking for, they will be loaded in with JSON and both php and javascript can natively handle JSON objects, while VBA doesn't. If the data is JSON formatted, it is much easier to parse it out of that than trying to parse it out of the DOM structure (DOM = document object model, another thing to google). Also, in many cases, if the data is loaded in with AJAX, it won't be returned with your winHTTP call, because that doesn't execute any javascript that might be in the page.
Further, in many cases you will need to set headers or cookies in the winHTTP call to get the data (calls without the right setings might return an error or a redirect). That is also not addressed in my answer, although you can set headers and cookies in winHTTP. You would need to sniff the calls, either with Fiddler or similar or with the network tab in dev tools, to find out the right combination of information to pass with your request.
I want to use Blockly to do some calculations, and then generate text files (as opposed to exporting code to JavaScript, Python, PHP, etc.)
I can’t see an obvious way to create my own blocks to do this in Blockly, so using AppInventor (Version: nb168), I got storing and retrieving files to work, in a crude test app on my Android tablet.
In AppInventor/Designer mode, clicking Storage/File creates a “Non-visible component for storing and retrieving files. Use this component to write or read files on your device.”
Then, in AppInventor/Blocks mode, clicking the “File1” icon gives access to 7 “file type blocks”, e.g. AppendToFile, Delete, ReadFrom, SaveFile, etc.
Is it possible to create similar “file type blocks” to use in Blockly Web?
I have limited programming knowledge, so would appreciate simple answers, please.
Thanks, Pete.
Andrew N Marshall from Google/Blockly has told me this:
"This is absolutely possible ...as long as you willing to work within the browser's security restrictions. The resulting files will be need to be manually "downloaded" one at a time, rather than written directly to the user's file system.
... I would start understanding what JavaScript functions are available to you. Attempt to construct a string and save it via a download dialog...
That means the "file" contents are really just a string in memory, a JavaScript variable. We have lots of "Text" blocks that can do a variety of operations on strings. If those are enough, you'll only need one new block to identify the string variable and initiate the download process.
Otherwise, you'll need to think about what blocks you want, and how they operate. They may operate on a specific variable in the JavaScript VM, not necessary exposed as a variable to Blockly.
Either way, you'll need to learn how to create a block and a Blockly app. We have a code lab that will walk you through all the steps. You'll learn how each block generates a string of code, and in your case, that code will be related to the download code I mentioned earlier."
So I'll press on - I just wanted to be sure my goal is actually achievable before I started.
Thanks, Pete.
I was trying to repro a tutorial about the creation of an Excel Add-in when something get wrong with the IntelliSense of Visual Studio. I was writing this code:
function updateStocks() {
Excel.run(function (ctx) {
var **range** = ctx.workbook.names.getItem("Stocks")
At this step, everything was fine, but after the getItem, I have tried to add .getRange() at which point the IntelliSense was not able to understand anything related to my variable range.
Screenshot
What is really "funny" is the fact that even if the properties are not displayed, when I write the code of the tutorial manually, the code is executed without mistake.
Why does this behavior occur and how can I correct it?
Are you able to see IntelliSense for other types within that .run? I.e., do you have everything up to the point where you get a Range from a named item? If you were to obtain the range differently (e.g., context.workbook.getSelectedRange()), do you get IntelliSense then?
This might be related to an issue (now fixed) where the CDN accidentally had the namedItem.getRange method removed (it was the only one that was affected, and we've put in measures to ensure we catch those in the future). See "Can't get range from a defined name". The CDN has been patched a couple weeks ago, but the JS IntelliSense file ("VSDOC") probably hadn't. If that's the case, it's a point-in-time issue that should resolve itself very very soon, as new deployments of the CDN will have the getRange method both in the VSDOC and everywhere else.
FWIW, you may still run into limitations of the JS IntelliSense engine (there are plenty, unfortunately: for example, trying to pass values across Promises, or passing in API objects as parameters to functions). The only true good workaround for this is using TypeScript, which allows you to declaratively assert to the compiler/IntelliSense-engine that "I know this type is an Excel.Range!") -- and offers a number of other goodies, async/await being a very major one. I personally believe that if you really want a "premier" Office.js-coding experience, TypeScript is the way to go. To that end, I describe how to use TypeScript in my book, "Building Office Add-ins using Office.js" (full disclosure, I am the author; but I've had many readers comment on how helpful of a resource it's been to them). The book is very much TypeScript-oriented, IntelliSense being one of the reasons (and async/await and let being the primary others) -- though I also offer an Appendix where I describe the JavaScript-only way of accomplishing the same Office.js tasks. It takes only a small amount of effort to get started with using TypeScript, and once you do, I don't think you'll look back.
I'm trying to do paging of results from a Cloudant database.
I've tried using bookmark, but the fact that the final page of results still has a bookmark is a problem for me, since it means that apps using the database can't tell if there's a 'next page' or not without requesting it.
Instead, I've tried using skip with a URL like this:
https://samdutton.cloudant.com/mydb/_design/mydesigndoc/_search/mysearch?
q=foo:bar&skip=10
However, this isn't working: I always get the first page of results.
Am I doing something wrong, or should this work?
Skipping results isn't supported in search. See the search documentation for the full list of supported options.
I'm using Unified Functional Testing v12.02 (or QTP).
Sometimes while running script i get the below error and sometimes I don't.
Cannot identify the object "..." (of class ...) Verify that this
object's properties match an object currently displayed in your
application.
Tip: If the objects in your application have changed, the Maintenance
Run Mode can help you identify and update your steps and/or the
objects in your repository.
I checked OR and the object itself with Spy tool and they have the same properties.
Sometimes I get the same error in other objects, but if I run again the script it works well.
Can someone explain me what might be the problem?
Im a little bit confused why sometimes i get these errors and sometimes don't.
I'm testing a simple web application (for training purposes)
Also I'm using the following add-ins: Web, Web-SAPUI5, Visual Basic
Mostly object wont be in the readystate. Check State of the Object using
Webedit(googlesearch).object.readyState="complete"
Webedit(googlesearch).object.Load
Webedit(googlesearch).object.Disabled=False