How to close windows file upload window when using selenium - java

I am trying to write selenium tests for a website using java. However, I have come across a problem when testing file uploading.
When I click the file upload button, it automatically opens the windows file upload. I have code working to put the file path ("D:\\test.txt") into selection. From researching this subject I understand there is no way for selenium webdriver to handle this. So my question is this: what is a way I can simply close the upload window in an automated way? Indeed the sendKeys working with selecting the txt file but the window upload still not closing.
Thanks in advance
ProductActionCode :
public static void AutoInsert_Execute(WebDriver driver) throws Exception {
ConfirmationPlaceBet_Page.btn_ChanShiOdd(driver).click();
ConfirmationPlaceBet_Page.btn_UploadOddTxt(driver).click();
ConfirmationPlaceBet_Page.btn_DocumentToBeUpload(driver).click();
ConfirmationPlaceBet_Page.pick_DocumentToBeUpload(driver).sendKeys("D:\\test.txt");
ConfirmationPlaceBet_Page.btn_ProceedUploadAuto(driver).click();
ConfirmationPlaceBet_Page.btn_ConfirmedUploadAuto(driver).click();
for (int i = 0; i < 3; i++) {
ConfirmationPlaceBet_Page.btn_AddDoubleBet(driver).click();
}
ConfirmationPlaceBet_Page.btn_ConfirmNumberToBet(driver).click();
for (int k = 0; k < 49; k++) {
ConfirmationPlaceBet_Page.btn_IncreaseBet(driver).click();
}
ConfirmationPlaceBet_Page.btn_ProceedBet(driver).click();
ConfirmationPlaceBet_Page.btn_ConfirmBet(driver).click();
}
ConfirmationPlaceBetCode :
public static WebElement pick_DocumentToBeUpload(WebDriver driver) throws Exception{
try{
driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS);
element = driver.findElement(By.name("file"));
Thread.sleep(500);
//Log.info("Pick Lottery1 ");
}catch (Exception e){
Log.error("Button is not found on the Confirmation Page");
throw(e);
}
return element;
}
HTML CODE :
<div id="filePicker" class="webuploader-container"><div class="webuploader-pick">选择文件</div><div id="rt_rt_1a24olu914nt122e1qls1c5l1b2qm" style="position: absolute; top: 0px; left: 0px; width: 86px; height: 30px; overflow: hidden; bottom: auto; right: auto;"><input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="text/*"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div>

You need to use sendkeys for same.
I assuming that you have a browse button and a button as upload
driver.findElement(By.xpath("YOUR XPATH")).sendKeys("Absolute path of file");
Feel free to change locator of an element in the above code
sendkeys will set the path and file name in the HTML for the respective upload field
Now click on upload button.
ConfirmationPlaceBet_Page.btn_ConfirmBet(driver).click();
Note:- put a wait between sendkeys and click on upload button. It helps many times
For more info refer below link:-
http://seleniumeasy.com/selenium-tutorials/uploading-file-with-selenium-webdriver
Hope it will help you :)

You can use these lines of code to close the upload window after sending the path of file with pressing ESCAPE Button
import java.awt.Robot;
import java.awt.event.KeyEvent;
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
For Example look at below code:
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver-v0.19.1-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://online2pdf.com/reduce-pdf-file-size");
WebElement element =driver.findElement(By.xpath("//*[contains(text(),'Select files')]"));
Actions ac = new Actions(driver);
ac.moveToElement(element).click().build().perform();
driver.switchTo().activeElement().sendKeys("C:\\Users\\eclipse-workspace\\Selenium\\abc.pdf");
Thread.sleep(300);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
}

Related

Java Selenium "Element Not Interactable Exception" when using sendKeys to open multiple tabs

I am trying to web scrape a Quebec government website for law names and their associated PDFs but when I try to open the tabs of all the different laws to get their PDF links, I get an ElementNotInteractable Exception when it attempts to open the 9th link. I tried opening the link by itself and it opens fine but when it is going through all the laws, it stops there and gives me that exception. Here is my code snippet:
static SortedMap<String,String> QuebecConsolidatedStatutesAndPDFs = new TreeMap<String,String>();
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\WorkSpace\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(5000));
driver.get("http://www.legisquebec.gouv.qc.ca/en/chapters?corpus=statutes&selection=all");
Thread.sleep(5000);
List<WebElement> QuebecConsolidatedStatutes = driver.findElements(By.xpath("//body/div/div/div[2]/div/div[2]/table/tbody/tr[contains(#class, 'clickable')]/td/a"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String parent = driver.getWindowHandle();
for (int i=0; i<QuebecConsolidatedStatutes.size(); i++){
String opentabs = Keys.chord(Keys.CONTROL, Keys.ENTER);
wait.until(ExpectedConditions.visibilityOf(QuebecConsolidatedStatutes.get(i)));
QuebecConsolidatedStatutes.get(i).sendKeys(opentabs);
}
There are several issues here:
The main problem is that you have to scroll the element you want to click on into the view. Your default initial screen height presents 8 rows while to click on 9-th row and more you have to scroll that element first into the view.
You could set driver window to better dimensions, this will show you more screen, however you will still have to scroll, but after 15 elements.
You should improve your locators.
You should not mix up WebDriverWait and implicitlyWait.
This should work better:
static SortedMap<String,String> QuebecConsolidatedStatutesAndPDFs = new TreeMap<String,String>();
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\WorkSpace\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(5000));
driver.manage().window().maximize();
driver.get("http://www.legisquebec.gouv.qc.ca/en/chapters?corpus=statutes&selection=all");
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("tr.clickable a"), 100));
Thread.sleep(300);
List<WebElement> QuebecConsolidatedStatutes = driver.findElements(By.cssSelector("tr.clickable a"));
String parent = driver.getWindowHandle();
for (int i=0; i<QuebecConsolidatedStatutes.size(); i++){
String opentabs = Keys.chord(Keys.CONTROL, Keys.ENTER);
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", QuebecConsolidatedStatutes.get(i));
Thread.sleep(300);
wait.until(ExpectedConditions.visibilityOf(QuebecConsolidatedStatutes.get(i)));
QuebecConsolidatedStatutes.get(i).sendKeys(opentabs);
}
}

Unable to locate the Element on Canvas using Selenium WebDriver

I have an application developed by using Vaadin Framework, Now i need to click on the rectangular polygon which is on the Canvas.following is the html code
here i am providing the Html code
<canvas width="1920" height="524" class="ol-unselectable" style="width: 100%; height: 100%;"></canvas>
and i tried by using Actions which makes the mouse move over the Polygon and click .
int x = (int) 5638326.333511386;
int y = (int) 2580101.9711508946;
driver.get("http://localhost:8080/internship");
WebElement ele = driver.findElement(By.xpath("//canvas[#class='ol-unselectable']"));
// driver.findElement(By.tagName("canvas"));
//driver.findElemet(By.className("ol-unselectable"));
try {
Actions builder = new Actions(driver);
builder.moveToElement(ele, x, y);
builder.clickAndHold();
builder.release();
builder.perform();
} catch (Exception e) {
// do nothing
}
i am getting the foloowing error
org.openqa.selenium.NoSuchElementException: Unable to locate element:
//canvas[#class='ol-unselectable'].
can anyone suggest some samples how to find polygon on canvas with co-ordinates and make click on it.
Usually, the canvas element is embedded in an iframe.
So, first, you have to find the iframe element and then find the canvas inside the iframe. For instance:
WebDriver driver = new FirefoxDriver(firefoxOptions);
try {
driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_empty");
WebElement iframe = driver.findElement(By.name("iframeResult"));
driver.switchTo().frame(iframe);
WebElement canvas = driver.findElement(By.id("myCanvas"));
System.out.println(canvas.getText());
} finally {
driver.quit();
}
I think this code might help you.
EDIT:
After chatting with #RamanaMuttana and his changes on the posted question, I could better understand his need.
We realized that just using the By.tagName selector was enough to find the canvas element as in the code bellow:
driver.findElements(By.tagName("canvas")).get(0);

How to continue a landscape orientation for a particular div tag while converting html to pdf in itext 7?

<div isLandscape=false style="page-break-after:always">
<p class="title">
this is the first title in the portrait mode
</p>
<div>
this is the content following the first title in portrait mode
</div>
</div>
<div isLandscape=true style="page-break-after:always">
<p class="title">
this is the first title in the Landscape mode
</p>
<div style="page-break-after:always">
this is the content following the first title in Landscape mode
</div>
<p>
This content which is on the next page should be rendered on a landscape
page and all the content in this parent div should continue to be in the
landscape page.
</p>
</div>
<div isLandscape=false style="page-break-after:always">
<p class="title">
this content should be rendered on the portrait page and continue to be on a
portrait page till the end of the parent div tag.
</p>
</div>
I want the first div content to be on the portrait A4 page and the next to be on the landscape A4 page.This should be not by rotation but by actually setting the pagesize.
One of the ways you can achieve this is by parsing to layout elements instead of straight to a file or pdfDocument, and apply the page size modification using page events.
I made a quick example below that switches orientation every X pages:
public void createPdfFromHtml(String htmlSource, String pdfDest, String resoureLoc) throws IOException, InterruptedException {
File pdf = new File(pdfDest);
pdf.getParentFile().mkdirs();
//convertToElements takes the string containing the HTML as input
byte[] bytes = StreamUtil.inputStreamToArray(new FileInputStream(htmlSource));
String html = new String(bytes);
PdfWriter writer = new PdfWriter(pdfDest);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc,pageSize);
// Create the page size modifying event handler
PageSize pageSize = PageSize.A4;
pageSize = pageSize.rotate();//Start in landscape
int differentPageSizeInterval = 5;
PageSizeModifier pageSizeModifier = new PageSizeModifier(doc, differentPageSizeInterval, pageSize);
//Register it to the pdfDocument and set it to trigger at the start of a page
pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE,pageSizeModifier);
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setBaseUri(resoureLoc);
//Convert the html to elements
try {
//parse and return the top level elements of the <body>
List<IElement> elements = HtmlConverter.convertToElements(html, converterProperties);
for (IElement ele : elements) {
//Add the elements to the layout document
doc.add((BlockElement) ele);
}
doc.close();
} catch (PdfException e) {
System.out.println(e);
e.printStackTrace();
}
}
protected class PageSizeModifier implements IEventHandler {
Document doc;
int interval;
int counter;
PageSize pageSize;
public PageSizeModifier(Document doc, int interval,PageSize pageSize) {
this.doc = doc; //A reference to the layout document must be kept so we can change the margins on the fly
this.interval = interval;
this.counter = 1;
this.pageSize = pageSize;//Start out in landscape
}
#Override
public void handleEvent(Event event) {
if(counter == interval){
//Rotate
pageSize = pageSize.rotate();
//For the rendering framework, change the default page size
doc.getPdfDocument().setDefaultPageSize(pageSize);
//because the page was already created, we need to update the various boxes determining the pagesize
//By default, only the trim and mediabox will be present
((PdfDocumentEvent) event).getPage().setMediaBox(pageSize);
((PdfDocumentEvent) event).getPage().setTrimBox(pageSize);
//Reset the counter
counter = 1;
}else{
counter++;
}
}

How to divide the webview content in multiple pages

I have to create PDF from my webView using PdfDocument on Android.
https://developer.android.com/reference/android/graphics/pdf/PdfDocument.html
The pdf is created well but it is only one page document.
// create a new document
PdfDocument document = new PdfDocument();
// create a page description
PageInfo pageInfo = new PageInfo.Builder(width,
height, 1).create();
// start 1st page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = myWebview;
content.draw(page.getCanvas());
// finish 1st page
document.finishPage(page);
// start 2nd page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = someOtherWebview;
content.draw(page.getCanvas());
// finish 2nd page
document.finishPage(page);
// and so on...
FileOutputStream out;
try {
out = new FileOutputStream(fileNameWithPath, false);
// write the document content
document.writeTo(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// close the document
document.close();
How can I divide webview content in pages?
I am creating an android app that reads a file like a book, but instead of chopping it up and displaying one page at a time, I hide all but one of the sections and then just display the entire file.
So perhaps you could use a similar technique something like:
1. You can hide all of the webview with css
2. reveal one section
3. write to the PDF
4. hide the previous section
5. reveal the next etc.
In your text.html source file read by your webview, wrap each page in div tags like this:
<div id="page1" style="display:hidden;">
Page 1 text
</div>
<div id="page2" style="display:hidden;">
Page 2 text
</div>
<div id="page3" style="display:hidden;">
Page 3 text
</div>
In your Java:
//First you have to enable Javascript
webView.getSettings().setJavaScriptEnabled(true);
//Then run this javascript which will find the first page and reveal it
webView.loadUrl("javascript:document.getElementById('page"+ 1 +"').style.display ='block';");
//reload Webview
webView.loadUrl("C:\Desktop\text.html");
//write to PDF
//repeat for page 2
hope this helps!

HTML code getter using SWT Browser

How I can get html-page code to String using SWT Broser?
Display display = new Display();
Shell shell = new Shell(display);
shell.setSize(100, 100);
Browser browser = new Browser(shell, SWT.NONE);
browser.setBounds(5, 75, 100, 100);
shell.open();
browser.setUrl("https://google.com");
String html = browser.getText(); //NOTHING!
while (!shell.isDisposed()) {
if (!display.readAndDispatch() && html == null) {
display.sleep();
}
}
display.dispose();
Syste.out.println(html); ////NOTHING!
So, how I can take html? And best way, when after html-code getting the display window will close?
The method you are searching for is: Browser#getText(). Here is the important part of the javadoc:
Returns a string with HTML that represents the content of the current page.
So this would do the job:
String html = browser.getText();
System.out.println(html);
For your second question: You can close the shell by calling Shell#close(). Here is the Javadoc:
Requests that the window manager close the receiver in the same way it would be closed when the user clicks on the "close box" or performs some other platform specific key or mouse combination that indicates the window should be removed.

Categories

Resources