We have a PDF link that opens in browser via the chrome built in PDF viewer. We are trying to verify the text in this PDF, without using PDFBox or downloading the file to our local system.
Our attempt uses Keys.chord to send "CTRL+A" and "CTRL+C" (both upper and lower case versions) to the browser. (This results in a big blue box selection rather than the line selection we see when trying copy paste manually). We think that there are sufficient delays of 2 seconds between the commands, yet the text content doesn't show up in the system clipboard (tested via pasting to notepad). Should we be sending these actions to a specific web element rather than "body" or "html"?
Additionally, when we try to use the Clipboard.getData(DataFlavor.stringFlavor) we get an unsupported flavor unicode string exception.
Any insight into copy pasting from the built in chrome pdf viewer via selenium would be appreciated.
// This results in a weird blue selection box
String selectAll = Keys.chord(Keys.CONTROL, "A");
webDriver.findElement(By.tagName("body")).sendKeys(selectAll);
Thread.sleep(2000);
String copyAll = Keys.chord(Keys.CONTROL, "C");
webDriver.findElement(By.tagName("body")).sendKeys(copyAll);
Thread.sleep(2000);
// Error happens here
String result = Toolkit.getSystemClipboard().getData(DataFlavor.stringFlavor);
I think you should use a instead if A
WebElement ele = webDriver.findElement(By.tagName("body"));
ele.sendKeys(Keys.chord(Keys.CONTROL, "a"));
Thread.sleep(2000);
similarly c instead of C
ele.sendKeys(Keys.chord(Keys.CONTROL, "c"));
Thread.sleep(2000);
String result = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
Related
I am trying to upload a file to a website using the HtmlUnit HtmlFileInput class. I have the data in a byte[] array and would like to send it up without writing it to a file first.
I'm trying:
HtmlFileInput fileInput = form.getInputByName("file");
fileInput.setData(data);
HtmlElement button = form.getInputByName("validate");
HtmlPage responsePage = button.click();
This is not working. But, when I try
HtmlFileInput fileInput = form.getInputByName("file");
fileInput.setValueAttribute("file.txt");
HtmlElement button = form.getInputByName("validate");
HtmlPage responsePage = button.click();
Everything works fine. The docs seem to indicate that setData() does exactly what I want to do, but it doesn't seem like any of the HtmlUnit code even uses the data_ variable that is set when setData() is called. The code uses the files_ field which is set when setValueAttribute() is called.
I noticed several old bugs that were opened that talked about similar problems and it says that they were all fixed.
Am I trying to use setData() in a way that it shouldn't be used?
Thanks.
In short - data_ is used by getSubmitNameValuePairs() and there are also unit tests for that (e.g. com.gargoylesoftware.htmlunit.html.HtmlFileInput2Test.setValueAttributeAndSetDataDummyFile()).
The trick here is the missing rest of the file - you have to simulate a bit more if you like to get your stuff uploaded. Please set the Value (to submit a dummy file name) and the content type also to help the server to understand your data.
HtmlFileInput fileInput = form.getInputByName("file");
fileInput.setValueAttribute("dummy.txt");
fileInput.setContentType("text/csv");
fileInput.setData("My file data".getBytes());
I think i have to improve the documentation for this a bit.
If you like we can discuss this or if you like to see a quick fix - simply open an issue on github.
I am using the Aspose library to convert PDF to HTML. But after conversion, I am facing a page fitting issue. On browser HTML file shows a white area on the right side. Does anyone have an idea of how to solve this issue?
Reference Link: https://docs.aspose.com/pdf/java/convert-pdf-to-html-format/
Code Snippet:
doc.setFitWindow(true);
doc.getPageInfo().setLandscape(true);
// Instantiate HTML Save options object
HtmlSaveOptions newOptions = new HtmlSaveOptions();
// Enable option to embed all resources inside the HTML
newOptions.PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml;
newOptions.LettersPositioningMethod = LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss;
newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats;
newOptions.setConvertMarkedContentToLayers(true);
// Output file path
String outHtmlFileName = new StringBuilder(source.getName().replaceAll(Constant.PDF_EXTENSION, "")).append(Constant.DASH).append(System.currentTimeMillis()).append(Constant.HTML_EXTENSION).toString();
String outFileName = new StringBuilder(targetDirectory).append(Constant.SLASH).append(outHtmlFileName).toString();
// Save the output file
doc.save(outFileName, newOptions);
How to do ctrl+f in webdriver/java? I have to do in a way where there are 2 excel sheets, each excel sheet contains list of email addresses. So need to copy each cell email, and search it in a web page. If it finds that email address in the web page then copy the corresponding data and save it in another excel sheet.
I know how to do ctrl+f5 using web driver, but ctrl+f is littly tricky. Any help is appreciated.
You can do it by using the Keys.chord() method:
driver.findElement(By.xPath("your-xpath")).sendKeys(Keys.chord(Keys.CONTROL, "f"));
or by using the Action class and the unicode representation:
Actions action = new Actions();
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0066')).perform();
For a full list of unicode characters read more here.
if(driver.findElement(By.XPath("//tagname[text()='mailID']")).isDisplayed){
// write your code
}
or
if(!driver.findElements(By.XPath("//tagname[text()='mailID']")).isEmpty){
// write your code
}
How to upload files from local via window prompt using selenium webdriver?
I want to perform the following actions:
click on 'Browse' option on the window
from the window prompt go to the particular location in the local where the file is kept
select the file and click on 'Open' to upload the file.
Have you tried using input() on proper file input control?
WebElement fileInput = driver.findElement(By.id("some id"));
fileInput.sendKeys("C:/path/to/file.extension");
I have used below three different ways to upload a file in selenium webdriver.
First simple case of just finding the element and typing the absolute path of the document into it. But we need to make sure the HTML field is of input type. Ex:<input type="file" name="uploadsubmit">
Here is the simple code:
WebElement element = driver.findElement(By.name("uploadsubmit"));
element.sendKeys("D:/file.txt");
driver.findElement(By.name("uploadSubmit"));
String validateText = driver.findElement(By.id("message")).getText();
Assert.assertEquals("File uploaded successfully", validateText);
Second case is uploading using Robot class which is used to (generate native system input events) take the control of mouse and keyboard.
The the other option is to use 'AutoIt' (open source tool).
You can find the above three examples : - File Uploads with Selenium Webdriver
Selenium Webdriver doesn't really support this. Interacting with non-browser windows (such as native file upload dialogs and basic auth dialogs) has been a topic of much discussion on the WebDriver discussion board, but there has been little to no progress on the subject.
I have, in the past, been able to work around this by capturing the underlying request with a tool such as Fiddler2, and then just sending the request with the specified file attached as a byte blob.
If you need cookies from an authenticated session, WebDriver.magage().getCookies() should help you in that aspect.
edit: I have code for this somewhere that worked, I'll see if I can get ahold of something that you can use.
public RosterPage UploadRosterFile(String filePath){
Face().Log("Importing Roster...");
LoginRequest login = new LoginRequest();
login.username = Prefs.EmailLogin;
login.password = Prefs.PasswordLogin;
login.rememberMe = false;
login.forward = "";
login.schoolId = "";
//Set up request data
String url = "http://www.foo.bar.com" + "/ManageRoster/UploadRoster";
String javaScript = "return $('#seasons li.selected') .attr('data-season-id');";
String seasonId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
javaScript = "return Foo.Bar.data.selectedTeamId;";
String teamId = (String)((IJavaScriptExecutor)Driver().GetBaseDriver()).ExecuteScript(javaScript);
//Send Request and parse the response into the new Driver URL
MultipartForm form = new MultipartForm(url);
form.SetField("teamId", teamId);
form.SetField("seasonId", seasonId);
form.SendFile(filePath,LoginRequest.sendLoginRequest(login));
String response = form.ResponseText.ToString();
String newURL = StaticBaseTestObjs.RemoveStringSubString("http://www.foo.bar.com" + response.Split('"')[1].Split('"')[0],"amp;");
Face().Log("Navigating to URL: "+ newURL);
Driver().GoTo(new Uri(newURL));
return this;
}
Where MultiPartForm is:
MultiPartForm
And LoginRequest/Response:
LoginRequest
LoginResponse
The code above is in C#, but there are equivalent base classes in Java that will do what you need them to do to mimic this functionality.
The most important part of all of that code is the MultiPartForm.SendFile method, which is where the magic happens.
in My case,when i retrieve string of different language from database and add it to paragraph of itext.it is not displayed properly.
it is displayed as::
???????????
code as ::
Paragraph quetion_cell_paragraph= new Paragraph(100);
String itemtext = new String(multipleChoiceSingleCorrect.getItemText().getBytes(),"UTF-8");
quetion_cell_paragraph.add(itemtext);
please let me know the solution.
try adjusting
Windows -> Preferences -> General -> Workspace (bottom left)
// Text file encoding, chose Other, UTF-8.