URL redirection automation in UFT/Selenium - selenium

A URL of a webpage is being changed to a new URL.There are 200 such old URLs that have changed to new URLs.
Test scenario :1.200 old URls with their corresponding new URLs are present in two different columns in an Excel sheet.When an old URL is entered in the address bar,it will be directed to the new URL in the browser.
Can the above test be automated via Selenium or UFT for 200 URLs?

You can do it more easily and much quicker by using Java HttpURLConnection class unless you are forced in a solution with Selenium\QTP
Open up the connection with the old link with the openConnection() method of URL class. Check for the response from getResponseCode() method. If response is not in 300 series then you have a problem. If response is in 300 series you have correct behaviour and check the redirected URL from the Location header.
Have a look at this link which will make things easier - https://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/

You have to do the Exact same way in QTP. But i have a doubt.
i.e. If you have new URLs the nwhy u will enter old urls in Browser addressBar ?
anyway u can look at the following
as u have said in Excel file old & new URL are mentioned Adjacent cells.
Then you might either use Following things to read excel file.
1) Create Excel.Application object
or
2) Use DataTabe to import Excel Sheet
or
3) U can use Excel as ADODB connection
now just read the old URL from that Excel file & take value from the New url column cells & store it in a Varriable(let say : strNewURL).
Then you can do this & use FOR loop
set IE= CreateObject("InternetExplorer.Application)
IE.Visible = True
'For loop here
' [intsomecount] is variabel which is teh no of times loops gonna iterate, in This case the Number of URL mentioned
For iterator=0 to intsomecount step 1
IE.Navigate strNewURL
wait 3
Next
lemme know if you concerns. :)

Related

Enter data into username and password fields using cell reference in selenium

Good morning everyone. I wrote this code in VBA to log into a website. I would like to do the exact same thing but using selenium. Is this possible? The reason I want to reference a cell for user name and password is because multiple people will be using this sub and I don't want one persons username/password to be embedded in the code and therefore can't use sendkeys. Here is the VBA code
'Search DOM for element by ID and input username
Set HTMLDoc = IE.Document
Set HTMLInput = HTMLDoc.getElementById("userName")
HTMLInput.Value = Worksheets("Sheet1").Range("B3").Text
Do you want to get the value of a cell in Excel only using selenium and implement automation?
If this is the case, then this is impossible, because selenium can only operate the browser, and to get the value in excel only through VBA code.
If you use VBA, you can combine them. Add Selenium Type Library in Reference. Then you can write code to achieve your automation needs. Simply refer to this thread.
Found the Solution:
'Input Username (Cells(row, column).value)
Ch.FindElementByName("userName").SendKeys (Cells(3, 2).Value)

VBA: Follow Link in existing Session - Excel

We have a Excel-List of URLs with a lot of parameters.
The problem is: The first time you follow a link, you get redirected to a ADFS-Login, which cuts some of the Parameters, since they have a maximum URL-length.
My question: Is there a possibility to tell excel (be it via VBA or default) to use an existing Session?
I tried some shennenigans, for example via Chrome: Find the Window handle for a Chrome Browser or to take an existing IE-Window: http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window.html While I get an existing Window, it seems like it always gets redirected and the URL cut. Is there anyhow a possibility to make this?
Please try this and post feedback
Open Sheet1
In Column A, from row 2 create your list of URLS
Insert ActiveXControl Microsoft Web Browser WebBrowser1
Size the control to your needs
Insert Control Button outside the bounds of the browser
Change name of the button to NextButton
Open Code Editor (Alt+F11)
In Sheet1 place the below code
Dim currentURLRow As Integer ''Sheet level variable
Sub NextButton_Click()
On Error Resume Next
Dim url As String
''VBA evaluates second expression even when the first of OR is true. So on error resume next helps here
If currentURLRow = 0 Or Trim(Cells(currentURLRow, 1)) = "" Then
''First time or loop back
currentURLRow = 2
Else
currentURLRow = currentURLRow + 1
End If
On Error GoTo 0 ''reset error so you know of any (good) errors
url = Cells(currentURLRow, 1)
''Sheet1.WebBrowser1.Silent = True ''Uncomment this if you are seeing lot of script errors that you dont want to see
WebBrowser1.Navigate url
Debug.Print WebBrowser1.Document.body.InnerHTML ''' Here you can do magic if the urls you are navigating are serialisable to objects :)
End Sub
Now the first time you navigate to the site, you should be prompted for user name and password, on click of next, your session to saved.

Using vbscript to log on to internet provider webpage (data in html table)

I'm sure that this is a repeat post, but I've been unable to find exactly what I need. I currently live on a college campus where I need to enter a username and password to use the internet. I'm trying to automate the process (using .bat files) so I can run a server application on startup without ever pressing a key. Unfortunately, I keep getting an error at line 9 char 9: "Object does not support this property or method: 'getElementByID'" I tried replacing .getElementByID with .getElementByName, but it didn't make a difference.
Call Main
Function Main
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate "https://caserver.jbu.edu/auth/perfigo_weblogin.jsp"
Wait IE
With IE.Document
.getElementByID("username").value = "name"
.getElementByID("password").value = "password"
.getElementByID("tx_voputilities_pi1[sign_in]")(0).Submit
End With
End Function
Sub Wait(IE)
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
End Sub
I think that the problem has to do with the webpage. The "username" and "password" fields are elements inside a table. I couldn't find an example webpage with similar properties, so I'm at a loss. I'm not sure if the authentication page can be viewed from off-campus, so I attached a picture with some of the HTML (or at least the elements list)
My research so far:
VBScript to Launch a website login
IE 9 error getElementbyId: Object required
VBScript get contents of html table text input field
VBS website login script - "Object required" error
Like I said, I'm using batch files to start a computer. I wanted this to be a quick (and, yes, crude) solution, but there may be a better way to automate webpage logon. If there is a [quick] better way, feel free to point me in the correct direction.
Your problem may be that they don't use id, but name instead.
There is no function getElementByName, but there is getElementsByname
You could try
.getElementsByName("username")[0].value = "name"
.getElementsByName("password")[0].value = "password"
(I should probably note that this assumes the first element with these names is the one you are looking for - names do not have to be unique hence the array returned and the lack of a getElementByName function, whereas id is unique)
As a further note, your problem is not that the fields are in a table - getting an element from the DOM with either getElementById or getElementsByName do not take positioning into account, only that the element exists somewhere within the parent you are running the function on.

Opening a file using impersonation

I have been searching the web looking for a way to open a WORD file from a secure network folder by impersonating a user who has access. The closest I've come to finding the answer was this from 2 years ago:
Impersonating in .net (C#) & opening a file via Process.start
Here is the code that I am using. When I set the arguments = LocalFile_Test, everything works perfectly because the user is accessing the local c:\ that is has access to. But when I set arguments = RemoteFile_Test, Word opens up a blank document which is the same effect as if I put garbage in the arguments. So it appears that it cannot find the file even though when I login with the user/domain/password that I specify in the properties below, I can find that exact file name and it is not empty. Does anything jump out at you right away? I appreciate your time.
Dim LocalFile_Test As String = "C:\New.docx"
Dim RemoteFile_Test As String = "\\Server1\Apps\File\New.docx"
Dim MyStartInfo As New System.Diagnostics.ProcessStartInfo
MyStartInfo.FileName = "C:\Program Files\Microsoft Office\Office12\WINWORD.exe "
MyStartInfo.Arguments = LocalFile_Test
MyStartInfo.LoadUserProfile = True
MyStartInfo.UseShellExecute = False
MyStartInfo.UserName = "specialuser"
MyStartInfo.Domain = "mydomainname"
MyStartInfo.Password = New System.Security.SecureString()
MyStartInfo.Password.AppendChar("p"c)
MyStartInfo.Password.AppendChar("a"c)
MyStartInfo.Password.AppendChar("s"c)
MyStartInfo.Password.AppendChar("s"c)
Process.Start(MyStartInfo)
My understanding is that you are trying to get a password protected file from a server, and when you do process start, it just opens up a blank word doc. I think the error is how you are trying to get the file, I think you have to map the actual physical path of the file on the server, like
System.Web.HttpContext.Current.Server.MapPath("\\Server1\Apps\File\New.docx")
From there, I am fairly certain, you need to create network credentials for the user like
System.Net.NetworkCredential=New NetworkCredential(userName:=, password:=)
Finally, once that is done, you can either write the file, or transmit the file like so...
System.Web.HttpContext.Current.Response.TransmitFile(file name)
System.Web.HttpContext.Current.Response.WriteFile(file name)
Then,once you get the file, you can try to open it with process start.
Hope that helps, let me know if what I said doesn't work.

How to write to a "Google Spreadsheet" from Excel 2003 VBA

I Have an Excel 2003 file with a line similar to this:
I need to click "the button" and it adds that line as the last one on a Google Spreadsheet
Similar to:
Is it possible?
Should I use the command-line Google tools?
Is there a better way? Easier way?
How would you do it?
(once I know how to add "stuff" from VBA to Google Docs, how the f do i add it to the last line?)
More info: I have an Excel 2003 "program" that saves all of the company's sales (with the customer info), and I'd like do make a global address book that's easily updated by my (non it) co-workers.
You don't need OAuth or the spreadsheet API. Google Spreadsheet allows data entry with a simple form, which means also that a HTTP POST will do the trick. You just need to prepare your spreadsheet to accept data entries via a form as follows:
Login to your Google Docs account
Create a spreadsheet or open an existing one
Click on Tools / Create a form
Add anything in the form description just to enable the Save button
Save the form
Copy the formkey value displayed in the link at the bottom of the form creation page
Now you can issue a simple post into the spreadsheet without OAuth
You can test the entry now with curl if you have it on your system (replace the formkey placeholder with the formkey from your table):
curl.exe -v -k "http://spreadsheets.google.com/formResponse?formkey=<formkey>" -d "entry.0.single=test&entry.1.single=test2&pageNumber=0&backupCache=&submit=Submit"
Next we try to execute the form POST from our Excel sheet via the following code. Add a reference to "Microsoft XML, v3.0" before. Replace column1 with your desired values.
Dim httpRequest as XMLHTTP
Set httpRequest = New XMLHTTP
httpRequest.Open "POST", "http://spreadsheets.google.com/formResponse?formkey=<formkey>&ifq", False
httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.Send "entry.0.single=" + column1 + "&entry.1.single=" + column2 + "&pageNumber=0&backupCache&submit=Submit"
'Check result in the following vars
httpRequest.status
httpRequest.statusText
Hope that helps
I had started answering your question, but realized that it was much less trivial than I thought it was when I started playing with the OAuth 2.0 API. I think it would be a lot easier if you could make your Google spreadsheet public, but I doubt that is advisable with sales data.
The reason this is non-trivial is the authentication part. The ASP OAuth below is probably usable with some work, but I noticed it uses Session variables and some other ASP objects, so you'd have to do a lot of tweaking.
In that light, here is my original answer, if it helps.
There is a google spreadsheet API:
https://developers.google.com/google-apps/spreadsheets/#adding_a_list_row
The OAuth 2.0 link that the spreadsheet docs refer to is out-of-date. You can play with the OAuth requests here, which should help you get started.
API functions are called by GET/POST requests with XML, which you can call using the XMLHTTP object.
First, reference Microsoft XML in your Excel project (Tools->References->Microsoft XML, v6.0)
In your VBA, you essentially use the following to send XML requests:
Dim x as MSXML2.XMLHTTP
Set x = New MSXML2.XMLHTTP
x.Open "POST", "http://example.com/", False
x.Send "<xmldata></xmldata>"
You should be able to adapt this OAuth 2.0 ASP library for your VBA code.
This is an ASP example of how to use that OAuth library; again since both the ASP and the VBA are using the VBScript syntax, it could probably be adapted.
I spent the last couple of days trying to find a good easy solution to this problem.
None seemed to work for me so I had to utilize bits and pieces from various posts I found on-line.
Steps to follow:
Create a Google spreadsheet
Create a form (under “Tools” – “Create a form”) with a three fields (you can add fields later after testing)
Go back to the Google spreadsheet and it should have created a new sheet (called "Form Responses") with headings matching the field names given when setting up the form.
Column A will automatically have as a heading “Timestamp” with your field names as headings for columns B, C & D etc.
Now click on “Form” – “Go to Live Form”
Write-click and “Inspect” (Ctrl-Shift-I) and click on Network
Enter some data (anything) for each of the respective fields and click on “Submit”
Click on “Headers” Click on “formResponse”.
Under “General” copy the url of the form. Note a “?” is required at the end of the url.
Also under headers find “Form Data”. This will be used in MyURL
Look for the entry.123456789 for each of the fields.
You will need these numbers for each field.
Replace xxxxxxxx in your code with your form's respective numbers.
Open up your Excel spreadsheet and copy in the sub-routine shown below
In the VBA editor click on Tools – References select the Microsoft XML.v3.0, (Microsoft XML Core Services)
Code:
Sub Write_Info_To_Google()
Dim ScriptEngine
Dim http As Object
Dim myURL As String
Set http = CreateObject("MSXML2.ServerXMLHTTP")
Set ScriptEngine = CreateObject("MSScriptControl.ScriptControl")
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
myURL = "https://docs.google.com/forms/d/e/ . . . . /formResponse?" & _
"entry.xxxxxxxxx=" + Cells(2, 1).Text + _
"&entry.yyyyyyyyy=" + Cells(2, 2).Text + _
"&entry.zzzzzzzzz=" + Cells(2, 3).Text
http.Open "GET", myURL, False
http.setRequestHeader "User-Agent", "Google Chrome 70.03538.102 (compatible; MSIE _
6.0; Windows NT 5.0)"
http.send
End Sub
Run this macro and watch your data from row 2 appear in the Google spreadsheet
Rather than use VBA in Excel, use a full fledged VB.NET application with the Excel Interop COM package. It's syntax is largely similar to the VBA commands, but to do the transferring to Google docs will be much easier in VB.NET.
Use the Google Documents List API to create a new spreadsheet.
Use the Google Spreadsheets API to move the data into your online spreadsheet.
Both Google APIs are REST APIs, so you'll have to use HttpRequest objects in VB.NET. Here is a great example of how to use them, just change the URLs so they are appropriate for Google. Google Spreadsheets even offers a library that abstracts away many of those steps.