How to get the title of a website page in VBA? - html

Here is a piece of code I have been working on to print the title of a window.
Dim my_title2 as Variant
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
MsgBox ("The number of pages is: " & IE_count)
For x = 0 To (IE_count - 1)
On Error Resume Next
my_url = objShell.Windows(x).document.Location
my_title = objShell.Windows(x).document.Title
If my_title Like "F-Engine" & "*" Then
Set ie = objShell.Windows(x)
my_title2 = ie.document.Title
'my_title2 = objShell.Windows(x).document.Title
MsgBox ("The wanted title for the page should corrrespond. " & my_title2)
Exit For
Else
End If
Next
I am having trouble printing the title of the window after Set ie = objShell.Windows(x).
When y_title2 = ie.document.title, the MsgBox displays:
"The wanted title for the page should correspond."
It prints nothing after this sentence. So the title assigned to "ie" is not being displayed.
If my_title2 = objShell.Windows(x).document.title, the MsgBox displays:
"The wanted title for the page should correspond. F-Engine"
Why am I not able to print the title of the page with the first declaration of my_title2?
I am doing this to verify if the page is being correctly picked up after a title "F-Engine" is found. To do so, I am trying to print the value of the title of the Internet Explorer window. It seems like nothing has been set and passed.

Not every object in objShell.Windows represents an IE page/tab - they might be instances of Windows Explorer. In those cases there is no document property to access.
You can test for this instead of using On Error Resume Next:
Dim w As Object, myUrl, myTitle, ie
For Each w In CreateObject("Shell.Application").Windows
If w.Name = "Internet Explorer" Then
myUrl = w.document.Location
myTitle = w.document.Title
Debug.Print myUrl, myTitle
If myTitle Like "F-Engine*" Then
Set ie = w
Debug.Print "Found: " & myTitle
Exit For
End If
End If
Next w

Related

Retrieve the value of a read-only input text box using VBScript

I'm working with an Internet Explorer based application where I need to retrieve the value of an input text box that is read only. I've looked at other Stack Overflow questions and don't see anything about getting the value of a read only or hidden input box. I haven't found anything I can use on the internet either.
Here's the HTML code for the input box I'm trying to get the value from:
<div class="col-xs-10 col-sm-9 col-md-6 col-lg-5 form-field input_controls">
<div class="hidden" ng-non-bindable="">
<input name="sys_original.x_opt_im_issue_task.number" id="sys_original.x_opt_im_issue_task.number" type="hidden" value="TSK0111065" />
</div>
<input class="form-control disabled " id="sys_readonly.x_opt_im_issue_task.number" readonly="readonly" ng-non-bindable="" value="TSK0111065" />
</div>
Here's the VBScript code I'm trying to use to get the value of the input text box that isn't working:
UPDATED
Option Explicit
Dim WShell, objShell, objIE
Dim strMessage, URL, ErrMsg, URLFound, Browser
Dim EN_ID, EntNowID
Sub Main()
On Error Resume Next
Set WShell = CreateObject("WScript.Shell")
Set objShell = CreateObject("Shell.Application")
If Err.Number <> 0 Then ShowError("Failed to create objects")
On Error GoTo 0
Check_EN
SetEverythingToNothing
End Sub
'---------------------------------
Sub ShowError(strMessage)
MsgBox strMessage & vbNewline & vbNewline & "Error number: " & Err.Number & vbNewline & "Source: " & Err.Source & vbNewline & "Description: " & Err.Description
Err.Clear
SetEverythingToNothing
End Sub
'------------------------------
Sub Check_EN()
URL = "https://enterprisenow.mysite.com"
ErrMsg = "EnterpriseNOW is not open or on the incorrect page. Please check & rerun the macro."
Check_URL
ErrMsg = ""
Set EN_ID = objIE.document.getElementById("sys_readonly.x_opt_im_issue_task.number")
EntNowID = EN_ID.Value
MsgBox EntNowID
End Sub
'------------------------------
Function Check_URL()
URLFound = False
For Each Browser In objShell.Windows()
If InStr(UCase(Browser.LocationURL), UCase(URL)) > 0 Then
If InStr(UCase(Browser.FullName), "IEXPLORE.EXE") Then
If Err.Number = 0 Then
Set objIE = Browser
URLFound = True
Exit For
End If
End If
End If
Next
If URLFound = False Then
MsgBox "Unable to find URL."
SetEverythingToNothing
End If
End Function
'-----------------------------
Sub SetEverythingToNothing()
Set WShell = Nothing
Set objShell = Nothing
Set Browser = Nothing
Set objIE = Nothing
End Sub
I'm able to set the objIE object and find the URL, but I'm receiving "Run-time error '424': Object required". Is it because the input text box is hidden or read only? I'm also wondering if it has anything to do with nested div tags?
Try the following - it worked for me. What I noticed is that if I accessed:
objIE.document.getElementById("sys_readonly.x_opt_im_issue_task.number").Value
more than once, I got the error: Object required
However if I used 'Set' and created an object like so:
Set tasknumber = objIE.document.getElementById("sys_readonly.x_opt_im_issue_task.number")
I could then access the value multiple times without receiving the error.
Option Explicit
Dim objShell : Set objShell = CreateObject("shell.application")
Dim URL : URL = "https://enterprisenow.mysite.com/"
Dim URLFound : URLFound = False
Dim Browser, tasknumber, tasknumbervalue
For Each Browser In objShell.Windows()
If InStr(UCase(Browser.FullName), "IEXPLORE.EXE") Then
If InStr(UCase(Browser.LocationURL), UCase(URL)) > 0 Then
If Err.Number = 0 Then
Set tasknumber = Browser.document.getElementById("sys_readonly.x_opt_im_issue_task.number")
If (NOT IsNull(tasknumber) And NOT tasknumber Is Nothing) Then
tasknumbervalue = tasknumber.value
End If
Set tasknumber = Nothing
Exit For
End If
End If
End If
Next
MsgBox tasknumbervalue
Set Browser = Nothing
Set objShell = Nothing
Well, it's not the solution I was hoping for, but it's easier than trying to get the number from the input field.
I had a feeling that the iframe tag may be preventing me from detecting the input field ID, so I looked at the iframe and saw that the TSK number in the input field was also in the iframe tag.
Instead of trying this:
EN_ID = objIE.document.getElementById("sys_readonly.x_opt_im_issue_task.number").Value
I was able to use this:
iframeName = Split(objIE.document.getElementById("gsft_main").Title, " | ") 'Title = "TSK0111065 | Issue Task | ServiceNow"
EN_ID = iframeName(0)

How is it possible to get the title of a webpage using vba?

Here is the code i wrote to get the titles of all the opened internet explorer pages on my computer.
Dim objShell As Object
Dim IE_count As Variant
Dim my_url As Variant
Dim my_title As Variant
Dim x As Integer
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
MsgBox ("The number of pages is: " & IE_count)
For x = 0 To (IE_count - 1)
On Error Resume Next
my_url = objShell.Windows(x).Document.Location
my_title = objShell.Windows(x).Document.Title
MsgBox ("The title of this page is: " & my_url)
The first MsgBox in my piece of code is actually displaying the correct number of IE_count (representing the number of windows opened).
However, I am having some trouble displaying the my_url or my_title variables.
The MsgBox related to these fields is just showing "The title of this page is: " and nothing after the "is".
Do you know how to fix this error in order to get the url or the title of a window?
PS: i even tried changing the data types from variant to string for my_url and my_title but nothing changed.
I would really appreciate any help! Thank you :)
Try removing this line:
Dim x As Integer
Edit:
What version of Excel are you using?
Perhaps '''Dim x As Variant''' will work.

IE automation: scrape <td> in <iframe> through VBA

I am trying to automate IE through VBA to click a button that is embedded in an "iframe" as on screenshot below (image in the last line):
However my code is unsuccesful in referencing the button (the last line doesn't print any value):
Sub intercept()
Dim my_title As String
my_title = "Accounting"
marker = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
On Error Resume Next ' sometimes more web pages are counted than are open
page_url = objShell.Windows(x).Document.Location
page_title = objShell.Windows(x).Document.Title
If page_title Like my_title & "*" Then 'compare to find if the desired web page is already open
Set IE = objShell.Windows(x)
marker = 1
Exit For
Else
End If
Next
If marker = 0 Then
MsgBox ("A matching webpage was NOT found")
Else
MsgBox ("A matching webpage was found")
End If
Set mytable = IE.Document.frames(1).Document.tables(1)
Debug.Print mytable.getElementsByTagName("td").Length
End Sub
I have also tried: IE.Document.frames(0).Document.tables(0).
Any help on how to click on this element is appreciated.

Editing HTML Code using Excel VBA

I am in need of editing html code using VBA. I actually got this working as far as editing values of text boxes. My problem is that when I simulate clicking the "submit" button there are new tables that come up. The web address stays the same but now there is new html code generated for the tables. I am trying to read data from these tables but it seems as if they don't exist when I try and query them. So I am guessing that I need to update or refresh the IE html code after I press the "submit" button. I can not seem to figure out how to do this. Any help is greatly appreciated. Here is my code so far:
Sub ImportStackOverflowData()
Dim SearchFor As IHTMLElement
Dim RowNumber As Long
RowNumber = 4
'to refer to the running copy of Internet Explorer
Dim ie As InternetExplorer
'to refer to the HTML document returned
Dim html As HTMLDocument
'open Internet Explorer in memory, and go to website
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate "http://google.com"
'Wait until IE is done loading page
Do While ie.ReadyState <> READYSTATE_COMPLETE
Application.StatusBar = "Trying to go to TRSDataBase ..."
DoEvents
Loop
Set html = ie.Document
Application.StatusBar = ""
'clear old data out and put titles in
Cells.Clear
Set SearchFor = html.getElementById("ddl_process")
'if this is the tag containing the question details, process it
If SearchFor.ID = "ddl_process" Then
'Replace the value of dl-process with copperhead name
Call SearchFor.setAttribute("value", "CPHB_FAT")
Cells(RowNumber, 1).Value = "Successfully replaced ddl_process to : " &
SearchFor.getAttribute("value")
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
Set SearchFor = html.getElementById("txt_startdate")
If SearchFor.ID = "txt_startdate" Then
'Replace the value of dl-process with copperhead name
Call SearchFor.setAttribute("value", "07-07-17")
Cells(RowNumber, 1).Value = "Successfully replaced startdate to : " &
SearchFor.getAttribute("value")
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
Set SearchFor = html.getElementById("txt_enddate")
If SearchFor.ID = "txt_enddate" Then
'Replace the value of dl-process with copperhead name
Call SearchFor.setAttribute("value", "07-14-17")
Cells(RowNumber, 1).Value = "Successfully replaced enddate to : " &
SearchFor.getAttribute("value")
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
'find view button and click it
Set SearchFor = html.getElementById("btn_header")
If SearchFor.ID = "btn_header" Then
SearchFor.Click
Cells(RowNumber, 1).Value = "The View Button has been clicked."
'go on to next row of worksheet
RowNumber = RowNumber + 1
End If
'Now get data from table after it loads
Application.Wait (Now + TimeValue("0:00:20"))
Set html = ie.Document <----------This is where i am trying to update or refresh my code after it loads with the new tables
Debug.Print ie.Document.body.innerHTML
Range("L5").Value = ie.Document.getElementsByTag("table")
(1).Rows(1).Cells(2).innerText
Try getting a new pointer to the window. Sometimes that does the trick.
Public Function FindWindow(SearchBy As String, SearchCriteria As String) As Object
Dim Window As Object
For Each Window In CreateObject("Shell.Application").Windows
If SearchBy = "URL" And Window.LocationURL Like "*" & SearchCriteria & "*" Then
Set FindWindow = Window
Exit Function
ElseIf SearchBy = "Name" And Window.LocationName Like "*" & SearchCriteria & "*" Then
Set FindWindow = Window
Exit Function
End If
Next
Set FindWindow = Nothing
End Function
Sub getNewPointer()
Dim ie As InternetExplorer
ie.Navigate "www.google.com"
'Wait for the page to load and do actions etc
'Your code here
'
'
'Clear the IE reference
Set ie = Nothing
'get a new pointer to the window of interest
'Keep in mind it finds the first matching Window based on your criteria!
Set ie = FindWindow("URL", "www.google.ca")
'Try getting the property you want
Debug.Print
End Sub

Click on a href link in an already opened browser window

In the below code I'm trying to click on the "About" link (href) in the www.google.co.in website. This worked on IE11 (Windows 10), but is not working for IE10 (Windows 7). Is this in anyway machine dependent. If not what is the right code?
Please remember I'm trying to click on a link in an already opened browser window.
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
On Error Resume Next ' sometimes more web pages are counted than are open
my_url = objShell.Windows(x).Document.Location
my_title = objShell.Windows(x).Document.Title
'You can use my_title of my_url, whichever you want
If my_title Like "Google" & "*" Then 'identify the existing web page
Set ie = objShell.Windows(x)
Exit For
Else
End If
Next
Dim LinkHref
Dim a
LinkHref = "//www.google.co.in/intl/en/about.html?fg=1"
For Each a In ie.Document.GetElementsByTagName("A")
If LCase(a.GetAttribute("href")) = LCase(LinkHref) Then
a.Click
Exit For ''# to stop after the first hit
End If
Next
You can achieve the goal with descriptive programming in QTP (if you don't want to use the object repository for some reason). This code should give you an example of what you can do:
Dim oDesc ' create a Description object for objects of class Link
Set oDesc = Description.Create
oDesc("micclass").value = "Link"
'Find all the Links in the browser using ChildObjects
Set obj = Browser("title=Google").Page("title=Google").ChildObjects(oDesc)
Dim i
'obj.Count value has the number of links in the page
For i = 0 to obj.Count - 1 ' indexed from zero, so use 0 to Count -1
'get the name of all the links in the page
If obj(i).GetROProperty("innerhtml")= LinkHref Then
obj(i).Click 'click the link if it matched the href you specfied
Exit For ' no need to carry on the loop if we found the right link
End If
Next
If you just need to use vbscript, you can do it like this:
Dim oShell : Set oShell = CreateObject("Shell.Application")
Dim oWindow
For Each oWindow In oShell.Windows
If InStr(oWindow.FullName, "iexplore") > 0 Then
If InStr(1, oWindow.Document.Title, "Google", vbTextCompare) > 0 Then
Set ieApp = oWindow
Exit For
End If
End If
Next
LinkHref = "//www.google.co.in/intl/en/about.html?fg=1"
For Each linky In ieApp.Document.GetElementsbyTagName("a")
If LCase(linky.GetAttribute("href")) = LCase(LinkHref) Then
linky.Click
Exit For
End If
Next
This is pretty much the answer given above by Ansgar, but with a little extra to fix the object error. Only a browser window has the Document.Title, and the loop is working through every window that's open, so you get the error when the loop tries a non IE window. This version fixes that by only checking for the Document.Title if the window has been identified as an IE instance in the first place.
Don't know about QTP, but VBScript doesn't have a Like operator.
This is the usual way to attach to an IE window with a specific title in plain VBScript:
Set app = CreateObject("Shell.Application")
For Each wnd In app.Windows
If wnd.Name = "Internet Explorer" Then
If InStr(1, wnd.Document.Title, "Google", vbTextCompare) > 0 Then
Set ie = wnd
Exit For
End If
End If
Next