Context-right click save link as - java

Using Java and Selenium, I am trying to get this link:
So from what I found, first I do a
Actions action = new Actions(driver);
scrollToElement(href);
action.contextClick(href).perform()
which brings up the menu, as it should. But then I do
action.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).build().perform();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
action.sendKeys(Keys.RETURN).build().perform();
However, that seems to do an arrow down OUTSIDE of the context menu.
This is a PDF link, so instead of selecting "Save link as", it hits the down arrow OUTSIDE of the context menu, so it closes the context menu, and just left-clicks on the pdf href.
So I am wondering about somehow having it move the arrow down while still in the context box. Or is there an xpath for "Save link as..."? I can't do an inspect on it. I suppose, I could try a
//*[contains(text(), 'Save link as"')]
but not sure that will work or not? Has anyone had this situation?

You're looking into wrong direction, you should not be automating file downloads as you're not testing your application, you're testing the browser and my expectation is that it is not something you should be doing.
Moreover, when you run your test remotely, i.e. in Selenium Grid or locally in parallel mode you will face issues as the browser which is not currently in focus will send key events to the application which is in focus.
The best option is extracting link href attribute value and performing the download using OkHttp library which is under the hood of Selenium Java Client. The relevant code would be something like:
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(href.getAttribute("href")).build();
Response response = client.newCall(request).execute();
File downloadedLogo = new File("myfile.pdf");
BufferedSink sink = Okio.buffer(Okio.sink(downloadedLogo));
sink.writeAll(Objects.requireNonNull(response.body()).source());
sink.close();

Related

Opening web link using only java (console)

Is there an option how to open a link using only console so for instance, If I enter 1 it will open a separate window where it will open my web link? I mean I want to use external links (URLs) where when I press 1 a chrome window will open with my URL. Is that possible and if so how, because I have only seen people do it using Java Swing. Any help would be great :)
Ok so I tried and this worked:
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://www.google.com");
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
You will also need to implement URI and java.awt library
Your question is not clear enough to me, but what I understood is that you want to open the website link from the browser console, if that's what you mean you can do it using this javascript code
For external URLs :
window.location = 'http (s): // www.example.com'
and for the internal URLs :
__ window.location = '/ file.php'
or window.location = '/ file.html'
or window.location = '/ your_route'
As I understand your description you want to open a web link based on an input (1 in your case) in your Java console app. You can use the method exec as the follownig:
try {
Runtime.getRuntime().exec("explorer https://www.google.com");
} catch(Exception e) {
e.printStackTrace();
}
here the exec method calls a command which here I call Google Chrome to open Google.com.
Using this in Windows will open the default browser showing the website.

How do I access an alert on a new window when the window hasn't loaded anything yet?

I'm running a Selenium script and at one point, we have a new window open and before anything in the window loads, an alert pops up. We switch to the new window and attempt to confirm the alert. This is the same kind of alert we see in other places, but when we try to confirm, or even just try to get the alert object itself, the script hangs, trying to forward getAlertText for the next 10 minutes.
Finally it fails:
[1568822219.289][SEVERE]: Timed out receiving message from renderer: 600.000
...which is no surprise. What I don't understand is why we can't get the alert, which looks the same as every other alert I've ever handled through Chrome and Selenium, and why it doesn't return a NoSuchAlertException instead of very-slowly failing. I cannot inspect the alert through the developer tools and it doesn't register as a window:
We're using driver.switchTo().alert(). I've also used the ExpectedConditions.alertIsPresent() condition. I've even tried accessing the alert before switching to the new window, which I had no real hopes of working, but when you have nothing logical left you try the illogical stuff.
Has anyone else had this issue? What did you do to overcome it? Thanks!
This alert cannot be handled using selenium to handle it you can use sikuli
same I have handled using sikuli
just import sikuli package and write code
String dir = System.getProperty("user.dir");
String allow = dir+"/extra/allow.png";
Screen s = new Screen();
Pattern allowimg = new Pattern(allow);
System.out.println("Trying to click on Allow popup...");
Thread.sleep(2000);
s.click(allowimg);

Selenium Java Client is not getting back the control once driver.get(URL) method is invoked

driver.get("MyURL");
System.out.println("URL is opened");
executeAutoItScript(scriptFileLocation);
when i open the URL i get an Authentication Required pop up.
To handle that I am using AutoIt script. But the problem is As soon as the first command
(driver.get("MyURL");)
is executed, Chrome will get open and the
Authentication pop up appears. And i have observed that the second line
System.out.println("URL is opened");
is not being executed. I debugged it and observed that the
control is not given to next line from
driver.get("MyURL");
and it hangs
there. I changed driver.get("MyURL"); to driver.navigate().to("MyURL"); but
there is no luck. Could anyone please help me to resolve this. Attached is
the pop up screenshot.
As per your code trials and the browser snapshot, it seems that the Browser Client (i.e. the Google Chrome Browser) is not returning back the control to the WebDriver instance and subsequently Selenium Java Client can't achieve the state of 'document.readyState' equal to "complete". Hence neither your next line of code:
System.out.println("URL is opened");
is getting executed, nor the AutoIt Script in next line:
executeAutoItScript(scriptFileLocation);
Solution
It is not clear from your question about the source of this Authentication Popup. Perhaps following the discussion Selenium - Basic Authentication via url you can pass the username and password being embedded within the URL as follows:
driver.get("http://admin:admin123#MyURL");
From: http://selenium-python.readthedocs.io/navigating.html
WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.
So, in this case your webpage is not fully loaded since it requires authentication. Here is what you can do
driver.get("MyURL");
executeAutoItScript(scriptFileLocation);
Thread.sleep(2000);// to wait for autoit script, you can also use other wait explicit wait
//Assert statement
System.out.println("URL is opened");
->First define the page load time for the driver.
->By using try-catch time out exception invoke the url.
->After that use robot class key events or key events class to enter the authentication details
Try the below one if any queries do lemme know:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
try{
driver.navigate().to("yourURL");
}
catch(TimeoutException te){
System.out.println(te);
System.out.println("Line went to Upto that Link");
after this you could proceed with the authentication pop-up code.
Do lemme know if you have any queries.
This helped me:
InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("initialBrowserUrl", "about:blank");
options.setPageLoadStrategy(PageLoadStrategy.NONE);
WebDriver driver = new InternetExplorerDriver(options);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.get(url);
//execute AutoItScript goes here

Selenium interacting with authentication popup

I have searched for this issue, and nothing that I've seen seems to work. I am currently trying to enter a username and password into an authentication box in Chrome, and I can't find a good way to do it in Selenium. The problem comes from the fact that running the "click" method on a webelement in Selenium effectively stops all execution until the authentication box has been dealt with. I've tried three approaches:
Before clicking on a webelement, create a new thread. In that thread, run
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Then run alert.authenticateUsing(new UserAndPassword("-ssqatest", "Sqa7-3$t"));
The problem with this is that alertIsPresent doesn't actually work in Chrome. I can confirm this by putting a print statement right after it, and it will never run, as it throws the error "cannot determine loading status". It works in Firefox, however, which leads me to the second attempt:
Doing it the same way as above, but in Firefox
This doesn't work because while the alert is detected properly, the line right after to authenticateUsing throws a selenium.Unsupportedcommandexception.
Directly typing in "https://username:password#url.com" into the Firefox browser after detecting the alert
This doesn't work because I can't use Selenium to get the URL of the page, since the webdriver was instantiated on the original thread, which got stopped during the authentication popup. I would prefer not to re-instantiate a new session just to get the URL of the page.
At this point, the only other method I can think of is to use java's Robot class, but I also would prefer not to do this, as it becomes quite messy with needing to manually have the robot have a keypress and keyrelease for each character.
What would be the best approach?
Thanks
You dont need to re-instantiate the thread. Unless im missing something you can go with #3 and just use switchTo() to change windows. Something like this:
Set<String> windowHandles = driver.getWindowHandles();
for(String handle : windowHandles) {
driver.switchTo().window(handle);
if(driver.getTitle().equals(NEW_WINDOW_TITLE)) {
return;
}
}

Selenium 2 WebDriver UnhandledAlertException Java

Now before I start getting scolded, I DID read through most of the existing questions about this and applied different solutions (which mostly repeat the same thing), but it still does not work for me.
I have a maven project with all necessary dependencies, and the website in testing is done specifically for IE and requires me to have a specific certificate in order to access it. I have the certificate for it, and when I go onto the website, before it loads the page it asks me to confirm that I have the certificate and I need to confirm on the pop-up window, THEN the login page fully loads.
I have done to typical:
WebDriverWait wait = new WebDriverWait(driver, 3);
try {
// Handle alert box
driver.navigate().to("https://ke.m-pesa.com/ke/");
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
catch(Exception e) {
//whatever
}
Can you tell me where I am going wrong? So far I have used only Selenium RC up till now so this webdriver stuff is still kind of new to me. Please tell me if you need any more info I need to provide.
Why do I still get the UnhandledAlertException?? and why can't I access the login page until I manually press the OK button?
Did you try using Robot? Something like :
Alert alert = driver.switchTo().alert();
Robot a = new Robot();
a.keyPress(KeyEvent.VK_ENTER);
Why robot and not Actions
From this answer :
There is a huge difference in terms of how do these tools work.
Selenium uses the WebDriver API and sends commands to a browser to
perform actions (through the "JSON wire protocol").
Java AWT Robot uses native system events to control the mouse and
keyboard.
If you are doing browser automation, ideally, you don't ever use
things like Robot since usually the functionality provided by selenium
is more than enough. Though, there are cases when there is a browser
or native OS popup opened, for example, to upload/download a file -
this is something that can be also solved with Robot -

Categories

Resources