Retrieve Data from Website with VBA Excel - vba

I understand there have been answered for similar questions but I am not sure if I could not understand how to approach to the solutions from other people' answers or my the website I need to get the information from is complex. So, please help me.
I would like to get the description field from Delphi for PN#13511996, the value should be "3 Way Gray GT 150 Sealed Female Connector Assembly, Max Current 15 amps" . Could someone help me examine the website and let me know how to get the description?
Sub GetData()
'Added Microsoft HTML Object library to reff
'Added Microsoft XML, v6.0 to reff
Dim xhr As MSXML2.XMLHTTP60
Dim doc As MSHTML.HTMLDocument
Dim desc As String
Set xhr = New MSXML2.XMLHTTP60
With xhr
.Open "GET", "http://ecat.delphi.com/feature?search=13511996", False
.send
If .ReadyState = 4 And .Status = 200 Then
Set doc = New MSHTML.HTMLDocument
doc.body.innerHTML = .responseText
End If
End With
With doc
desc = .getElementsByClassName("ProductDetail.Description").Item(0).innerText
End With
Debug.Print desc
End Sub

This is because you are requesting raw HTML by using GET from XMLHTTP. If you try to Debug.Print doc.body.innerHTML, you will see that the table has not been generated yet, and the text you are looking for is not there at all.
To be able to run the query for item "13511996", you need a real browser. Only then you can generate your table and get DOM document object. Try the following code:
Sub GetData()
Dim aIE As InternetExplorer
Dim desc As IHTMLElement
Set aIE = New InternetExplorer
With aIE
.navigate "http://ecat.delphi.com/feature?search=13511996"
.Visible = True '----> set it to false if you dont want to see the browser
End With
Do While (aIE.Busy Or aIE.ReadyState <> READYSTATE_COMPLETE)
DoEvents
Loop
Set desc = aIE.document.getElementsByClassName("DetailAttributes")(0)
'Debug.Print desc.innerText '---> prints the whole table data
Debug.Print Split(desc.innerText, vbLf)(3) '----> prints the forth data in table
Set aIE = Nothing
Set desc = Nothing
End Sub
And also if you plan to automate this code to run in a loop for multiple queries, you might want to use:
Set desc = Nothing
For i = 1 To 100
On Error Resume Next
Set desc = aIE.document.getElementsByClassName("DetailAttributes")(0)
If Err.Number = 91 Then
GoTo Skip
End If
Exit For
Skip:
Application.Wait (Now() + TimeValue("00:00:001"))
Next i
instead of:
Set desc = aIE.document.getElementsByClassName("DetailAttributes")(0)
This is because sometimes web page seems ready before it fully generates its contents. This causes the code to get out of do loop and proceed to next statement which sets desc object. You won't get an error while setting it because the code will be using previous DOM document object and will be outputting the results of your previous query, which is a bug. Without any errors, your code will run the loop till the end, and you will have a completely twisted output in your hand, which is a waste of time.
To work around this problem, you should set the object to nothing beforehand, and catch the error and wait for the page to load in for loop.
Last but not least, if the guys who build the web page that you are parsing are aware of what they are doing, they will probably protect it from multiple queries from the same source (most likely from multiple sources as well), which might cause their server to collapse if they don't. This protection will be reflected to you as limited number of queries within a limited amount of time. In other words, for example after 100 request within 5 minutes, the web page will not be responding for sometime (for example 2 minutes).
To workaround this problem, you should limit the number of requests and wait for the required time. Suppose that you increment your loop with i variable. Then you need to insert this at the end of your loop:
If i Mod 100 = 0 Then
Application.Wait (Now() + TimeValue("00:02:00"))
End If
I hope the above mentioned solutions solve everyone's past and future problems, which took me a considerable amount of time to figure out.

Related

How to avoid runtime error 5152 when trying to add a URL as shape to a Word document

I am trying to place a QR code generated through an API (api.qrserver,com) in a Word table using VBA. For certain reasons, the option of simply using "DisplayBarcode" is not possible.
This is the call to the API:
sURL = "https://api.qrserver.com/v1/create-qr-code/?data=" & UTF8_URL_Encode(VBA.Replace(QR_Value, " ", "+")) & "&size=240x240"
It seems to work well. I tried with a GET command and retrieved a string that - as I interpret - contains the QR code in png format.
Now, when I try to add the picture as a shape using
Set objGrafik = ActiveDocument.Shapes.AddPicture(sURL, True)
the call fails with runtime error 5152. As far as I could determine until now, the Addpicture method expects a pure filename and does not allow any of the following characters: /|?*<>:".
I also tried to store the GET result in an object variable:
Set oQRCode = http.responseText
but there I get the error "object required".
Research on the internet regarding a solution to either make the URL assignment work or to store the result as a picture didn't retrieve any useful results. Thanks in advance for your support
I am not sure that any of the ways you could insert something into Word (e.g. Shapes.AddPicture, InlineShapes.AddPicture, Range.InsertFile etc. will let you do that from any old https Url, although it seems to work for some Urls.
However, as it happens, you can use an INCLUDEPICTURE field to do it. FOr example
{ INCLUDEPICTURE https://api.qrserver.com/v1/create-qr-code/?data=Test&size=100x100 }
Here's some sample VBA to do that
Sub insertqrcode()
Dim sUrl As String
Dim f As Word.Field
Dim r1 As Word.Range
Dim r2 As Word.Range
' This is just a test - plug your own Url in.
sUrl = "https://api.qrserver.com/v1/create-qr-code/?data=abcdef&size=100x100"
' Pick an empty test cell in a table
Set r1 = ActiveDocument.Tables(1).Cell(5, 4).Range
' We have to remove the end of cell character to add the field to the range
' Simplify
Set r2 = r1.Duplicate
r2.Collapse WdCollapseDirection.wdCollapseStart
Set f = r2.Fields.Add(r2, WdFieldType.wdFieldIncludePicture, sUrl, False)
' If you don't want the field code any more, do this
f.Unlink
' check that we have a new inline shape that we could work with more
' if necessary
Debug.Print r1.InlineShapes.count
Set f = Nothing
Set r2 = Nothing
Set r1 = Nothing
End Sub
Using INCLUDEPICTURE works even on the current version of Mac Word (although I haven't tested that specific piece of VBA on Mac).
The only other way I have seen to do it uses WinHTTP to get the result from the web service, ADODB to stream it out to a local disk file, then AddPicture or whatever to include that file, so much more complicated and won't work on Mac either.

VBA webscraper stopped working on unexpected reason

I am coding VBA web-scraping software to grab products names from web and add them into Excel worksheet. This code was working fine a minute ago and then all of a sudden it stopped scraping the information. Any ideas what might be the problem? Website is still up and running and no inspected variables have been changed. Here is my code:
Dim http As New XMLHTTP60, html As New HTMLDocument, x As Long
With http
.Open "GET", "https://www.notebooksbilliger.de/pc+hardware/grafikkarten+pc+hardware/amdati/rx+6600+amdati/", False
.send
html.body.innerHTML = .responseText
End With
Do
x = x + 1
On Error Resume Next
Cells(x + 1, 1) = html.querySelectorAll("div.product_name a")(x - 1).innerText
Loop Until Err.Number = 91
I even recovered last save which was working 100% too and now it doesn't. I have not added anything else to the code nor changed references.
Is it possible that after multiple tests webpages block data scraping for some times?
I found out that the problem with this code and this specific website is that if you do multiple query's very often then you will be locked out for uncertain time.

Connect to data after having found an already open IE window using shell application

VBA code to interact with specific IE window that is already open
Above is a thread to find and go to an already open instance of IE using shell applications in VBA. AFTER I found the open IE instance I am looking for, I need to query the tables from that IE page without using it's URL. The reason that I cannot use it's URL is that this IE page is a generic 'result' page that opens in a separate window after doing a search on the main website, so if I use the URL of the result page, which is: https://a836-acris.nyc.gov/DS/DocumentSearch/BBLResult, it will return an error. Are there any other methods that allow querying tables without using URL connections, like a "getElements" for tables?
K.Davis, Tim William: you are correct in your assumptions. The first part of my code/project opens up a search page: objIE.navigate "https://a836-acris.nyc.gov/DS/DocumentSearch/BBL" and through it I submit a search form. The second part (outlined above in the first paragraph) opens up a result page (pop-up). I am trying to automate the retrieving of the tables from that page. I tried using QueryTables.Add method, the way I am familiar with to connect to the data/webpage requires an URL. If I use the URL from the result page it returns an error, thus I am looking for suggestions/help on how I could otherwise connect. That said I am able to retrieve elements of the page using 'getElements' method but not able to query tables. There are other ways to connect to the data source using the QueryTables.Add method, see, https://learn.microsoft.com/en-us/office/vba/api/excel.querytables.add but I am not familiar with these other methods. Hope this clarifies a bit.
I haven't experienced a problem with this as although you have an intermediate window the final IE window resolves to being the main IE window with focus. I was able to grab the results table with the following code using the indicated search parameters:
Option Explicit
Public Sub GetInfo()
Dim IE As New InternetExplorer
With IE
.Visible = True
.navigate "https://a836-acris.nyc.gov/DS/DocumentSearch/BBL"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
.querySelector("option[value='3']").Selected = True
.querySelector("[name=edt_block]").Value = 1
.querySelector("[name=edt_lot]").Value = "0000"
.querySelector("[name=Submit2]").Click
End With
While .Busy Or .readyState < 4: DoEvents: Wend
Dim hTable As HTMLTable
Set hTable = .document.getElementsByTagName("table")(6)
'do stuff with table
.Quit
End With
End Sub
You can copy a table via clipboard. Any tick windings appear in the right place but as empty icons.
For clipboard early bound go VBE > Tools > References > Microsoft-Forms 2.0 Object Library.
If you add a UserForm to your project, the library will get automatically added.
Dim clipboard As DataObject
Set clipboard = New DataObject
clipboard.SetText hTable.outerHTML
clipboard.PutInClipboard
ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).PasteSpecial
Late bound use
Dim clipboard As Object
Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

Internet Explorer OLE error in Excel VBA

I get the follow error from the click line: "Microsoft Excel is waiting for another application to complete an OLE action." How can I solve this? Thanks for your help.
It really annoys me becuase I can't even get the program to stop running, even by pressing several combinations of escape keys, so I have to restart my computer.
Set objCollection = IE.document.getElementsByTagName("a")
i = 0
While i < objCollection.Length
If objCollection(i).Title = "The maximum amount of records that may be downloaded is 2,000." Then
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click
Better to use a "For each" to browse through all of the anchors:
Dim objCollection, obj
For each obj in objCollection
If obj.Title = "The maximum amount of records that may be downloaded is 2,000." Then
Set objElement = obj
Exit For
End If
Next obj
I'm assuming there will only be the one result that you are looking for which is why i included the exit clause. This is quite vital as you don;t want the code to continue executing after it has found what you are after...

Automation Errors: 800706B5, 80004005, 80010108 appear for internal SAP site scrape

I am writing a macro that will scrape my company's internal SAP site for vendor information. For several reasons I have to use VBA to do so. However, I cannot figure out why I keep getting these three errors when I attempt to scrape the page. Is it possible that this has something to do with the UAC integrity model? Or is there something wrong with my code? Is it possible for a webpage using http can be handled differently in internet explorer? I am able to go to any webpage, even other internal webpages, and can scrape each of those just fine. But when i attempt to scrape the SAP page, i get these errors. The error descriptions and when they occur are:
800706B5 - The interface is unknown (occurs when I place breakpoints before running the offending code)
80004005 - Unspecified error (occurs when I don't place any errors and just let the macro run)
80010108 - The Object invoked has disconnected from its clients. (I can't seem to get a consistent occurrence of this error, it seems to happen around the time that something in excel is so corrupted that no page will load and i have to reinstall excel)
I have absolutely no idea what is going on. The Integrity page didn't make much sense to me, and all the research I found on this talked about connecting to databases and using ADO and COM references. However I am doing everything through Internet Explorer. Here is my relevant code below:
Private Sub runTest_Click()
ie.visible = True
doScrape
End Sub
'The code to run the module
Private Sub doTest()
Dim result As String
result = PageScraper.scrapeSAPPage("<some num>")
End Sub
PageScraper Module
Public Function scrapeSAPPage(num As Long) As String
'Predefined URL that appends num onto end to navigate to specific record in SAP
Dim url As String: url = "<url here>"
Dim ie as InternetExplorer
set ie = CreateObject("internetexplorer.application")
Dim doc as HTMLDocument
ie.navigate url 'Will always sucessfully open page, regardless of SAP or other
'pauses the exection of the code until the webpage has loaded
Do
'Will always fail on next line when attempting SAP site with error
If Not ie.Busy And ie.ReadyState = 4 Then
Application.Wait (Now + TimeValue("00:00:01"))
If Not ie.Busy And ie.ReadyState = 4 Then
Exit Do
End If
End If
DoEvents
Loop
Set doc = ie.document 'After implementation of Tim Williams changes, breaks here
'Scraping code here, not relevant
End Function
I am using IE9 and Excel 2010 on a Windows 7 machine. Any help or insight you can provide would be greatly appreciated. Thank you.
I do this type of scraping frequently and have found it very difficult to make IE automation work 100% reliably with errors like those you have found. As they are often timing issues it can be very frustrating to debug as they don't appear when you step through, only during live runs To minimize the errors I do the following:
Introduce more delays; ie.busy and ie.ReadyState don't necessarily give valid answers IMMEDIATELY after an ie.navigate, so introduce a short delay after ie.navigate. For things I'm loading 1 to 2 seconds normally but anything over 500ms seems to work.
Make sure IE is in a clean state by going ie.navigate "about:blank" before going to the target url.
After that you should have a valid IE object and you'll have to look at it to see what you've got inside. Generally I avoid trying to access the entire ie.document and instead use IE.document.all.tags("x") where 'x' is a suitable thing I'm looking for such as td or a.
However after all these improvements although they have increased my success rate I still have errors at random.
My real solution has been to abandon IE and instead do my work using xmlhttp.
If you are parsing out your data using text operations on the document then it will be a no-brainer to swap over. The xmlhttp object is MUCH more reliable. and you just get the "responsetext" to access the entire html of the document.
Here is a simplified version of what I'm using in production now for scraping, it's so reliable it runs overnight generating millions of rows without error.
Public Sub Main()
Dim obj As MSXML2.ServerXMLHTTP
Dim strData As String
Dim errCount As Integer
' create an xmlhttp object - you will need to reference to the MS XML HTTP library, any version will do
' but I'm using Microsoft XML, v6.0 (c:\windows\system32\msxml6.dll)
Set obj = New MSXML2.ServerXMLHTTP
' Get the url - I set the last param to Async=true so that it returns right away then lets me wait in
' code rather than trust it, but on an internal network "false" might be better for you.
obj.Open "GET", "http://www.google.com", True
obj.send ' this line actually does the HTTP GET
' Wait for a completion up to 10 seconds
errCount = 0
While obj.readyState < 4 And errCount < 10
DoEvents
obj.waitForResponse 1 ' this is an up-to-one-second delay
errCount = errCount + 1
Wend
If obj.readyState = 4 Then ' I do these on two
If obj.Status = 200 Then ' different lines to avoid certain error cases
strData = obj.responseText
End If
End If
obj.abort ' in real code I use some on error resume next, so at this point it is possible I have a failed
' get and so best to abort it before I try again
Debug.Print strData
End Sub
Hope that helps.