Upload files using selenium - java

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.

Related

Selenium Copy & Paste from PDF to System Clipboard

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);

HtmlUnit HtmlFileInput.setData() not working

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.

java print the redirected url

original url : http://pricecheckindia.com/go/store/ebay/52440?ref=velusliv
redirected url : http://www.ebay.in/itm/Asus-Zenfone-6-A600CG-A601CG-White-16-GB-/111471688863?pt=IN_Mobile_Phones&aff_source=DA
I need a program that will take the original url and print the redirected url.
How to get this done in java.
public static void main(String[] args) throws IOException, InterruptedException
{
String url = "http://pricecheckindia.com/go/store/ebay/52440?ref=velusliv";
Response response = Jsoup.connect(url).followRedirects(false).execute();
System.out.println(response.url());
}
It seems that you are being redirected via JavaScript code, which Jsoup doesn't support (it is simple HTML parser, not browser emulator). Your choice then is to either use tool which will support JavaScript like Selenium web driver, or parse your page to get url from click here link from
If it is taking too long to redirect, then please click here
text.
You can use Jsoup to get this link by adding to your current code
Document doc = response.parse();
String redirectUrl = doc.select("a:contains(click here)").attr("href");
System.out.println(redirectUrl);
which will return and print
http://rover.ebay.com/rover/1/4686-127726-2357-15/2?&site=Partnership_PRCCHK&aff_source=DA&mpre=http%3A%2F%2Fwww.ebay.in%2Fitm%2FAsus-Zenfone-6-A600CG-A601CG-White-16-GB-%2F111471688863%3Fpt%3DIN_Mobile_Phones%26aff_source%3DDA
so now all we need to do is parse query from this URL to get value of mpre key, which encoded version looks like
http%3A%2F%2Fwww.ebay.in%2Fitm%2FAsus-Zenfone-6-A600CG-A601CG-White-16-GB-%2F111471688863%3Fpt%3DIN_Mobile_Phones%26aff_source%3DDA
but after decoding it will actually represents
http://www.ebay.in/itm/Asus-Zenfone-6-A600CG-A601CG-White-16-GB-/111471688863?pt=IN_Mobile_Phones&aff_source=DA
To get value of this key and decode it you can use one of solutions from this question: Parse a URI String into Name-Value Collection. With help of method from accepted answer in previously mentioned question we can just invoke
URL address = new URL(redirectUrl);
Map<String,List<String>> urlQuerryMap= splitQuery(address);
String redirected = urlQuerryMap.get("mpre").get(0);
System.out.println(redirected);
to see result
http://www.ebay.in/itm/Asus-Zenfone-6-A600CG-A601CG-White-16-GB-/111471688863?pt=IN_Mobile_Phones&aff_source=DA

Download all images like wget does with Java on client-side

It's perfectly easy to download all images from a website using wget.
But I need this feature on client-side, best would be in Java.
I know wget's source can be accessed online, but I don't know any C and the source is quite complex. Of course, wget has also other features which "blow up the source" for me.
As Java has a built-in HttpClient, yet I don't know how sophisticated wget really is, could you tell me if it is hard to re-implement the "download all images recursively" feature in Java?
How is this done, exactly? Does wget fetch the HTML source code of the given URL, extract all URLs with the given file endings (.jpg, .png) from the HTML and downloads them? Does it also search for images in the stylesheets that are linked in that HTML document?
How would you do this? Would you use regular expressions to search for (both relative and absolute) image URLs within the HTML document and let HttpClient download each of them? Or is there already some Java library that does something similar?
In Java you could use the Jsoup library to parse any web page and extract anything you want
For me crawler4j was the open source library to recursively crawl (and replicate) a site, e.g. like this (their QuickStart example):
(it also supports CSS URL crawling)
public class MyCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|gif|jpg"
+ "|png|mp3|mp3|zip|gz))$");
/**
* This method receives two parameters. The first parameter is the page
* in which we have discovered this new url and the second parameter is
* the new url. You should implement this function to specify whether
* the given url should be crawled or not (based on your crawling logic).
* In this example, we are instructing the crawler to ignore urls that
* have css, js, git, ... extensions and to only accept urls that start
* with "http://www.ics.uci.edu/". In this case, we didn't need the
* referringPage parameter to make the decision.
*/
#Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches()
&& href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
#Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
Set<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
}
}
More webcrawlers and HTML parsers can be found here.
Found this program which downloads images. It is open source.
You could get the images in a website using the <IMG> tags. Look into the following question. It might help you.
Get all Images from WebPage Program | Java

How can I inject an XML file using Selenium?

I have the path to my XML file on my computer, but how can I use selenium (web automation tool) to inject the XML file ?
Usually how it is done (manually) is navigate to the URL and COPY AND PASTE the entire XML text into the provided text box..
Any ideas how to inject the file using automation ? There is no way to "drag" the XML file to the text box and I believe the way I'm thinking that it will work is very complicated.
I think this is actually what you want -
File xml = new File("xmlpath");
String url = xml.getAbsolutePath();
url = url.replace('\\', '/');
url = url.replace(" ", "%20");
String actual = "file:/" + url;
selenium.open(actual);
Then you should be able to get the xml using String theXML = selenium.getText("//rootxmlnode"); Then do what you will with it.
Check out the topic of Data Driven Testing to get you started. Something like this should get you going.
Selenium tool allows you to create an automatically generated code in Java.
So, you need to place any text in the provided text box and generate this Java-test code.
Next step is modifying of the generated test. You have to manually write a simplest code, which will read your XML file, get it contents and paste into the text box. The last thing is replacement (in the generated Java code of test!) of the mentioned above text-block to the contents of read XML.
A simplest way for reading file into a string is using Apache commons-io library.
For example: FileUtils.readFileToString(File file, String encoding) gives you a string object with contents of the file.

Categories