How to handle a file upload button using selenium? - selenium

I am trying to access the file upload element from a webpage and handle it to upload a file and click on submit for processing. Please tell me how to handle the file upload dialog boxes? Also when using the code, it got struck-ed in the find element module itself. What can i do for that?

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C); // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON); // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH); // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path
r.keyPress(KeyEvent.VK_ENTER); // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

Related

how can I show the pdf file content inside from razor file

I created a document file from word and has exported as pdf . i want to show the pdf content inside the Div element in razor page. How can I show the pdf content from razor page. Please can you provide an example code how to show in blazor server side
If you stored your pdf file directly in your documents for example in the folder wwwroot/pdf.
wwwroot/pdf/test.pdf
You can display this PDF with this line of html bellow :
< embed src="pdf/test.pdf" style="width=100%; height=2100px;" />
It will provide you a pdf displayer with printing options !
If you want to go further, upload your file and then display it, I will recommend you to go check this explanation :
https://www.learmoreseekmore.com/2020/10/blazor-webassembly-fileupload.html
The upload for PDF files works the same as Img file, you need to go check IBrowserFile documentation.
You will see that it has a Size obj and a OpenReadStream() function that will help you get the display Url for your file (image or pdf)
If the site abow closes, this is the upload code that is shown on it :
#code{
List<string> imgUrls = new List<string>();
private async Task OnFileSelection(InputFileChangeEventArgs e)
{
foreach (IBrowserFile imgFile in e.GetMultipleFiles(5))
{
var buffers = new byte[imgFile.Size];
await imgFile.OpenReadStream().ReadAsync(buffers);
string imageType = imgFile.ContentType;
string imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
imgUrls.Add(imgUrl);
}
}
}
This code was written by Naveen Bommidi, author of the blog where I found this usefull code
If you want, as I said, upload a PDF and then display it.
You can use the same html line :
< embed src="#imgUrl" style="width=100%; height=2100px;" />
And your uploaded files will be displaying.
Example

Protractor File Upload to a Link

I'm trying to upload a file using protractor and typescript. The upload button is on a toolbar that holds two other buttons as well. Unlike many of the examples I saw here, this upload button is implemented as a link and not an input.There is this warning in the console. There is no error, but the file isn't getting uploaded.
Warning below:
more than one element found for locator By(css selector, a.mat-icon-button) - the first result will be used
HTML below :
This is how I am trying to upload the file.
const fileToUpload = './Test_file.xlsx';
const absolutePath = path.resolve(__dirname, fileToUpload);
const uploadlink = element(by.css('a.mat-icon-button'));
uploadlink .sendKeys(absolutePath);
In that situation, if you are working in the Windows environment, I recommend looking into AutoIT.
It's very simple to script and use.
https://www.autoitscript.com/site/
more than one element found for locator By(css selector,
a.mat-icon-button) - the first result will be used
If you have 3 elements, and 3rd one is the element that handles upload, other 2 are just a link ref ?
Try to write more specific locator to the "upload" a tag.
can you verify on clicking of the button, if an input is present inside the code?
If there is no other solution use AutoIt.
const fileToUpload = './Test_file.xlsx';
const absolutePath = path.resolve(__dirname, fileToUpload);
const uploadlink = element(by.css('a.mat-icon-button>span.mat-button-wrapper>div.command-text'));
uploadlink .sendKeys(absolutePath);
If the above doesn't help try javascript executer
https://blog.ng-book.com/executing-raw-javascript-in-protractor/

Handle download dialog box in SlimerJS

I have written a script that clicks on a link which can download a mp3 file. The problem I am facing is when the script simulates the click on that link, a download dialog box pops up like this:
Download Dialog Box
Now, I want to save this file to some path of my choice and automate this whole process. I am clueless on how to handle this dialog box.
Here's a script adapted from this blog post to download a file.
In SlimerJS it is possible to use response.body inside the onResourceReceived handler. However to prevent using too much memory it does not get anything by default. You have to first set page.captureContent to say what you want. You assign an array of regexes to page.captureContent to say which files to receive. The regex is applied to the mime-type. In the example code below I use /.*/ to mean "get everything". Using [/^image/.+$/] should just get images, etc.
var fs=require('fs');
var page = require('webpage').create();
fs.makeTree('contents');
page.captureContent = [ /.*/ ];
page.onResourceReceived = function(response) {
if(response.stage!="end" || !response.bodySize)
{
return;
}
var matches = response.url.match(/[/]([^/]+)$/);
var fname = "contents/"+matches[1];
console.log("Saving "+response.bodySize+" bytes to "+fname);
fs.write(fname,response.body);
phantom.exit();
};
page.onResourceRequested = function(requestData, networkRequest) {
//console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.open("http://....mp3", function(){
});
You can't control a dialog box. SlimerJS doesn't have API for this action.
Firefox generates a temp "downloadfile.extension.part" file which contains the content. Just simply rename the file ex. myfile.csv.part > myfile.csv
locally if working on a mac you should find the .part file in the downloads directory, on linux /temp/ folder
Not the most elegant solution but should do the trick

Create FullPage Screenshot WebDriver

Does someone knows a way to create full page screenshots using WebDriver?
I want if one of my tests fails to create a FULL PAGE (even the not visible part on the screen) screenshot before the browser close and save it on share location.
Also, if it is possible I want to output the result to Jenkins Console log.
Thanks!
You can use the following extension for Firefox: https://addons.mozilla.org/nl/firefox/addon/fireshot/
You can find its javascript code in %APPDATA%\Mozilla\Firefox\Profiles\
The extensions provide the ability to copy the screenshot to the clipboard.
You can use its JS methods to perform the screenshot. After that, you can retrieve the image from the clipboard and save it to as a file on shared location.
Image image = default(Image);
if (Clipboard.GetDataObject() != null)
{
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap))
{
Image image = (Image)data.GetData(DataFormats.Bitmap,true);
image.Save("image.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
Console.WriteLine("The Data In Clipboard is not as image format");
}
}
else
{
Console.WriteLine("The Clipboard was empty");
}
string newImageName = string.Concat(#"C:\SampleSharedFolder\", Guid.NewGuid());
image.Save(newImageName );
Console.WriteLine("Image save location: {0}", newImageName);
Once you have populated the result to Console it is really easy to output it back to Jenkins. You can find more in my article: http://automatetheplanet.com/output-mstest-tests-logs-jenkins-console-log/
You can use Snagit to perform full page screenshots. More information here: https://www.techsmith.com/tutorial-snagit-documentation.html
First you need to start the Snagit server and then follow the documentation.

How do I grab hold of a pop-up that is opened from a frame?

I am testing a website using WatiN.
On one of the pages I get a "report" in an Iframe, within this I frame there is a link to download and save the report. But since the only way to get to the link is to use frame.Link(...) the pop-up closes immediately after opening; Code snippet below
//Click the create graph button
ie.Button(Find.ById("ctl00_ctl00_ContentPlaceHolder1_TopBoxContentPlaceHolder_btnCreateGraph")).Click();
//Lets export the data
ie.Div(Find.ById("colorbox"));
ie.Div(Find.ById("cboxContent"));
ie.Div(Find.ById("cboxLoadedContent"));
Thread.Sleep(1000);//Used to cover performance issues
Frame frame = ie.Frame(Find.ByName(frameNameRegex));
for (int Count = 0; Count < 10000000; Count++) {double nothing = (Count/12); }//Do nothing I just need a short pause
//SelectList waits for a postback which does not occur.
try
{
frame.SelectList(Find.ById("rvReport_ctl01_ctl05_ctl00")).SelectByValue("Excel");
}
catch (Exception)
{
//Do nothing
}
//Now click export
frame.Link(Find.ById("rvReport_ctl01_ctl05_ctl01")).ClickNoWait();
IE ieNewBrowserWindow = IE.AttachTo<IE>(Find.ByUrl(urlRegex));
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(150);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
I have tried using ie instead of frame which is why all those ie.Div's are present.
if I use frame the pop-up window opens and closes instantly.
If I use ie I get a link not found error.
If I click on the link manually, while the test is "trying to find the link" the file will download correctly.
I have changed the code to use a different page that doe not have the frame and I still get the same problem download pop-up closes instantly.
[STAThread]
public void TestForMeterDataExport()
{
// Open a new Internet Explorer window and
// goto the website.
IE ie = new IE("https://<URL>", true);
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler("C:\\Documents and Settings\\karnold\\Desktop\\MeterUsageReport_Large.xls");
Regex urlRegex = new Regex("<URL>\\?Mode=true&ReportID=[a-z A-Z 0-9]{30,33}&ControlID=[a-z A-Z 0-9]{30,33}&Culture=1033&UICulture=1033&ReportStack=1&OpType=Export&FileName=BuildingMeterDataReport&ContentDisposition=OnlyHtmlInline&Format=Excel");
//Find the Username text field and input the user ID
ie.TextField(Find.ByName("ctl00$ContentPlaceHolder1$txtUsername")).TypeText("<Name>");
//Find the Password text field and input the password
ie.TextField(Find.ByName("ctl00$ContentPlaceHolder1$txtPassword")).TypeText("PASS");
//Go ahead and login
ie.Button(Find.ByName("ctl00$ContentPlaceHolder1$butLogin")).Click();
//Let's use the Reports Tab
ie.Link(Find.ByUrl("https://<URL>")).Click();
// Let's get the meter data
ie.Link(Find.ByUrl("https://<URL>")).Click();
//Let's choose University of
ie.SelectList(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_TopBoxContentPlaceHolder_TopBoxContentPlaceHolder_ucFacility_ddlFacility")).SelectByValue("5041");
//Set the date range for which we want to get data
ie.TextField(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_TopBoxContentPlaceHolder_TopBoxContentPlaceHolder_DateRangePicker1_dpBeginDate_TextBox")).TypeText("12/09/10");
ie.TextField(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_TopBoxContentPlaceHolder_TopBoxContentPlaceHolder_DateRangePicker1_dpEndDate_TextBox")).TypeText("12/10/10");
//Click the create report button
ie.Button(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_TopBoxContentPlaceHolder_TopBoxContentPlaceHolder_btnSubmit")).ClickNoWait();
//Lets export the data
Thread.Sleep(2000);
//SelectList waits for a postback which does not occur.
try
{
ie.SelectList(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_ContentAreaContentPlaceHolder_ContentAreaContentPlaceHolder_rvMain_ctl01_ctl05_ctl00")).SelectByValue("Excel");
}
catch (Exception)
{
ie.SelectList(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_ContentAreaContentPlaceHolder_ContentAreaContentPlaceHolder_rvMain_ctl01_ctl05_ctl00")).FireEventNoWait("onchange");
//fire the postback event
}
//Now click export
ie.Link(Find.ById("ctl00_ctl00_ctl00_ContentPlaceHolder1_ContentAreaContentPlaceHolder_ContentAreaContentPlaceHolder_rvMain_ctl01_ctl05_ctl01")).ClickNoWait();
IE ieNewBrowserWindow = IE.AttachTo<IE>(Find.ByUrl(urlRegex));
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(10);
fileDownloadHandler.WaitUntilDownloadCompleted(20);
}// close TestForMeterDataExport()
Hopefully some one can tell me what I am doing wrong. Thank you
Here is the error that I get when the program can't find the handle maybe it will help
TestCase 'M:WebTest.CommandLine.WatiNConsoleWebAndDB.TestForMeterDataExport'
failed: Error HRESULT E_FAIL has been returned from a call to a COM component.
System.Runtime.InteropServices.COMException (0x80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.
at SHDocVw.IWebBrowser2.get_Document()
at WatiN.Core.Native.InternetExplorer.IEBrowser.get_NativeDocument()
at WatiN.Core.Native.InternetExplorer.IEWaitForComplete.WaitForCompleteOrTimeout()
at WatiN.Core.WaitForCompleteBase.DoWait()
at WatiN.Core.DomContainer.WaitForComplete(IWait waitForComplete)
at WatiN.Core.Native.InternetExplorer.AttachToIeHelper.FinishInitializationAndWaitForComplete(IE ie, SimpleTimer timer, Boolean waitForComplete)
at WatiN.Core.Native.InternetExplorer.AttachToIeHelper.Find(Constraint findBy, Int32 timeout, Boolean waitForComplete)
at WatiN.Core.Browser.AttachTo(Type browserType, Constraint constraint, Int32 timeout)
at WatiN.Core.Browser.AttachTo(Type browserType, Constraint constraint)
at WatiN.Core.Browser.AttachTo[T](Constraint constraint)
Web+DB_test_app.cs(139,0): at WebTest.CommandLine.WatiNConsoleWebAndDB.TestForMeterDataExport()
Thanks to Baptiste for the pointer.
//Set the handles and the file save as name
FileDownloadHandler handler = new FileDownloadHandler("MeterUsageReport_Large_Iframe.xls");
// add a watcher to look for the save file local
ie.AddDialogHandler(handler);
//Do not close dialog boxes immediately
ie.DialogWatcher.CloseUnhandledDialogs = false;
//create a single use instance that will be easily cleaned up and avoid having windows open after we are done with them
using (new UseDialogOnce(ie.DialogWatcher, handler))
{
//Now click export
frame.Link(Find.ById("rvReport_ctl01_ctl05_ctl01")).ClickNoWait();
//Grab hold of the poup dialog and download the file
handler.WaitUntilFileDownloadDialogIsHandled(30);
handler.WaitUntilDownloadCompleted(35);
}
Now for the fun this will only work if all of the work is done on localhost.
if you need to hit a server that is not local and ou want to use IE well then
2) You will need to edit the security for "trusted sites to allow scripting of downloads and Iframes.
* a) open IE
* b) Tools -> Internet options
* c) Security tab.
* d) make sure "trusted site" is highlighted
* e) click custom level, Make sure all .Net and .Net reliant components are set to enabled.
* f) Enable or prompt all activeX components
* g) Enable all downloads
* h) Enable .Net framework setup
* i) Enable scripting of web browser controls
* j) Enable allow websites to open windows without address's or status bars.
* k) Enable Launching programs or files from an Iframe.
* l) Everything under scripting is set to enabled or prompt.
* Just so you know, localhost is treated as a "low" security area so tests run on localhost do not need these changes.
* Refer to http://support.microsoft.com/kb/174360