WebDriver - how to get a page already open without modification - java

I need to enter a protected website.
Security requires a username and password, but with graphical components of Windows (no web code, like upload a file for example).
To skip this step, I coded a small Awt.Robot, which find and valid the 'pop-up' windows.
So I am with a web page open in the expected state.
How can I regain control, from this state, with WebDriver?
some kind of :
​​driver FirefoxDriver = new FireFoxDriver();
driver.get (page already open without modification and authentification);
Ideas?

To answer your question, it's not possible to take control of the already existing browser instance.
Some discussions:
How to use a already opened firefox for testing in Selenium

Getting around the JS popups is not easy and straightforward, using Robot solution is flaky. It will not work on Remote browsers etc.
Send username and password through url like http://username:password#your-app.com. Did you try something like below?
String url = "http://username:password#your-app.com";
driver.get(url);

Thanks to you, nilesh, I had an idea. I write for anyone who might encounter the same difficulty. My solution is made ​​very simple, I instantiate my driver and just before the get(url), I run my AWT.Robot is now a Thread. This allows me to not be bothered by the blocking property of driver.get(url);
private boolean openBrowserOnPage() {
try {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// run the robot which extends Thread
RobotHabile robot = new RobotHabile();
robot.start();
// Open the browser
driver.get(url);
// Wait for robot action
while(robot.isAlive()){
// not much, wait
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erreur : Impossible de se connecter/acceder au service '" + url + "'");
}
return false;
}
Hoping to help someone

For Purus, I will try again.
If I use WebDriver.driver.get(http://localhost/repository); the green popup appears, and that's all. The method will never finish. (1). This evil popup isn't a web component (not div, span, link, etc..) it's just a OS component (here Windows). It's impossible to manipulate this one with WebDriver.
So, just before WebDriver.driver.get(http://localhost/repository); I use a new class RobotHabile which extends Thread and use AWT.Robot.
The AWT.Robot can use keyboard, so when the evil popup appears(green), the Thread 1 is waiting for validation of the popup and with my RobotHabile robot = new RobotHabile();
robot.start();
With Thread 2 I can press my id, press tab for swith to password, press my pwd, and to finish press enter (2) .The robot does not target id and pwd fields. But as the popup already has focus, I can only fill with any character and tab key and enter. At this moment the evil popup is validate and the Thread 1 can normally continue.
better for your understanding ?

Related

Selenium chrome driver (Java) click() login button doesn't work programmatically but works manually

I'm just doing some test automation of web UI, specifically this page https://autorefi.capitalone.com/login/
I am locating the lastname, zipcode, ssn input boxes and typing in data (the data here doesn't matter). I am then simply using the locator to click the "Sign In" button. The problem is, everytime I run this within my code (Java) using selenium/chromedriver, I get an error
Sorry, we weren't able to log you in. If you continue to see this error, make sure you're using one of our supported browsers.
The problem is this is not the correct error message. You can try this yourself by simply opening another tab and entering a random lastname, zipcode, and last 4 digit of SSN. Conversely, if you actually had an offer with Capital one, it would bring up a different page completely. The point is, the first error message I posted only comes via selenium and is not correct. The correct error message is:
Sorry, it looks like you don't have an offer with Capital one.
I tried sleeping the thread before clicking the button ,because I thought it was maybe clicking it too fast, but it still didn't work. I a bit perplexed why doing the same set of operations manually seems to work, but launching this programmatically through selenium. Can anyone provide any insight here? My code is:
WebElement element;
WebDriver driver = null;
ChromeOptions options = new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.NONE);
driver = new ChromeDriver(options);
WebDriverManager.getInstance(CHROME).setup();
// TODO: PROD
driver.get("https://autorefi.capitalone.com/login/");
WebElement refiCommonLoginForm = new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.tagName("refi-common-login-form")));
WebElement shadowRoot1 = expandRootElement(refiCommonLoginForm, driver);
WebElement refiCommonLastName = shadowRoot1.findElement(By.tagName("refi-common-last-name"));
WebElement refiCommonLastNameShadowRoot = expandRootElement(refiCommonLastName, driver);
WebElement refiCommonZip = shadowRoot1.findElement(By.tagName("refi-common-zip"));
WebElement refiCommonZipShadowRoot = expandRootElement(refiCommonZip, driver);
WebElement refiCommonLastFourSSN = shadowRoot1.findElement(By.tagName("refi-common-last-four-ssn"));
WebElement refiCommonLastFourSSNShadowRoot = expandRootElement(refiCommonLastFourSSN, driver);
refiCommonLastNameShadowRoot.findElement(By.id("loginLastName")).sendKeys("random last name");
refiCommonZipShadowRoot.findElement(By.id("loginZipCode")).sendKeys("43978");
refiCommonLastFourSSNShadowRoot.findElement(By.id("loginLastFourSSN")).sendKeys("3483");
Thread.sleep(2000);
shadowRoot1.findElement(By.tagName("button")).click();
Absolutely not sure the issue is that, but still possibly this will help.
Instead of clicking the "Sign in" button try submitting it i.e. shadowRoot1.findElement(By.tagName("button")).submit()
But I guess the issue here is that this site has some kind of anti bot defense that blocks automated access to it.

Sendkeys without element selenium java

I'm trying to write a simple java based selenium code where I would load a page, give the desired values to username & password.
Once the page loads username is already focused but I can enter values into username or password
Using MAC - Eclipse
I am new to coding sorry so any help would be greatfully received
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://dc1.racbusinessclub.co.uk/login/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(2000);
driver.findElement(By.tagName("body")).sendKeys("rac-dc");
Thread.sleep(2000);
driver.findElement(By.tagName("body")).sendKeys(Keys.TAB);
Thread.sleep(2000);
Below is basic way of doing it.
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
pause(3);
WebElement button = driver.findElement(By.tagName("button"));
button.sendKeys(Keys.RETURN);
And once logged-in you can assert the url like below
Assert.assertTrue(driver.getCurrentUrl().endsWith("/yourURL"));
You can get username and password id from the browser by Right click on the page and select Inspect.
Even if the field is already focused, you must specify which element you wish to "send the keys" to. So grab the id of the username field, and then use sendKeys, like so:
driver.findElement(By.id("userNameInputBox")).sendKeys("rac-dc");
Also, worth noting that using Thread.sleep in your scripts is bad practice. If there's something you're waiting for, check for the presence of that element, rather than waiting an arbitrary amount of time.
Edit: Actually, seeing your response above I can see you're trying to interact with an alert popup, which you can do with:
driver.switchTo().alert().sendKeys(yourString);
Alternatively, you can skip that entirely and navigate to the page with your credentials in the URL - remember not to hard-code these:
driver.get("http://username:password#http://dc1.racbusinessclub.co.uk/");

selenium chrome driver select certificate popup confirmation not working

I am automating tests using selenium chromewebdriver 3.7. Whenever I lauch the site, I get a certificate selection popup like the one below
However I am not able to click on the OK button. These are the options I have tried
//I have tried getWindowHandle like this
String handle= driver.getWindowHandle();
this.driver.switchTo().window(handle);
//I have alos tried switching and accept
driver.switchTo().alert().accept();
//I have also tried to force the enter key like this
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// I also tried this way
Scanner keyboard = new Scanner(System.in);
keyboard.nextLine();
All my trials have failed. How can I click on OK on this popup window?
This is the closest solution I found which is not working Link here
I also had problems with accepting the warning for using a signed certificate. The solution of #eskoba worked like a charm. The functions are NOT final, because I let the enter button press for 10 times. I made this, because the webdriver needs a long time until it actually calls the url. In the meantime he starts pressing already.
In Python:
def threaded_function():
#Calls the website
browser.get(url)
def threaded_function2():
#Presses 10 times
for i in range(0,10):
pyautogui.press('enter')
#Calling the website and pressing 10 times in the same time
thread2 = Thread(target = threaded_function2)
thread2.start()
thread = Thread(target = threaded_function)
thread.start()
If still actual, I had same issue on Mac, and solution was simple:
for chrome is set AutoSelectCertificateForUrls policy like that:
defaults write com.google.Chrome AutoSelectCertificateForUrls -array-add -string '{"pattern":"[*.]example.com","filter":{"ISSUER":{"CN":"**cert issuer**"}, "SUBJECT":{"CN": "**cert name**"}}}'
for safari:
security set-identity-preference -c "**cert name**" -s "**example.com**"
then use it in code like
subprocess.call() in python
I had the same problem and I was able to solve it by using the robot, creating function for the url and passing it to a different thread.
Runnable mlauncher = () -> {
try {
driver.get(url);
} catch (Exception e) {
e.printStackTrace();
}
};
public void myfunction {
try {
Thread mthread = new Thread(mlauncher);
mthread.start
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception e) {
e.printStackTrace();
}
One suggestion would be, use Sikuli to click on OK button in the certificate.
Steps:
Take screenshot of OK button and save it.
Download sikuli-script.jar and add it to Project's Build path.
Take a screenshot of the UI Element to be clicked and save it locally.
Add the following code to the test case.
Screen s=new Screen();
s.click(“image name”);
Other functions Sikuli provides can be found here.
You can also skip being prompted when a certificate is missing, invalid, or self-signed.
You would need to set acceptInsecureCerts in DesiredCapabilities and pass that when you create a driver instance.
for example, in Python:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.CHROME.copy()
caps['acceptInsecureCerts'] = True
driver = webdriver.Chrome(desired_capabilities=caps)

Selenium Driver (Chrome) Can't Find Dropdown on hover Element

I'm using the Selenium Chrome Driver to run a couple tests on various site environments, however, when attempting to use an element from a hover drop down menu, I can't seem to reliably select the elements. This works 100% of the time when I'm debugging, but when I run it without an attached debugger it fails about 2/3rds of the time. Here is the code:
private void prepWindow(WebDriver driver, boolean isNightly, String toClick) {
WebDriverWait wait = new WebDriverWait(driver, 300);
try {
if (isNightly) {
WebElement nightlyPopup = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(BOWebElements.nightlyPopup)));
nightlyPopup.click();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Nightly popup has changed names again.", "Error", JOptionPane.ERROR_MESSAGE);
}
WebElement user = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Users")));
Actions action = new Actions(driver);
action.moveToElement(user).build().perform(); //Makes hover drop down appear
driver.findElement(By.id(toClick)).click(); //Should click element that is only visible when hover drop down is open
}
I should also note that the same code above works perfectly without using a debugger on a coworker's computer, but not my own.
I would like to use XPath but unfortunately the elements of the drop down aren't actually children of the link I have to hover over to open the drop down. If I try to navigate directly to the element using the XPath, it gives me an error saying the XPath isn't valid. Here is one of the potential XPaths:
//html/body/#outTemplateId/#preambleFormId/#globalNavigation/#navBGC/#navBGCmainMM/ul/li/ul/table/tbody/tr/td/ul.ui-menu-list.ui-helper-reset/li.ui-menuitem.ui-widget.ui-corner-all/a#fleetUsersId2.ui-menuitem-link.ui-corner-all.submenu
How can I make the behavior consistent?
Chain your actions together to better emulate the actions that a user would take:
action.moveToElement(user).moveToElement(driver.findElement(By.id(toClick))).click().build().perform();
Check out this question for more details:
https://stackoverflow.com/a/17294390/3537915

Java Selenium Web Scraping Upload Image [duplicate]

I have seen lots of questions and solutions on File upload using Selenium WebDriver on Stack Overflow. But none of them are working for following scenario.
Someone has given a solution as following
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
But still I can't find window handle. How can I work on that?
I am looking for a solution for the scenario above.
Please check this on any of the following websites.
http://www.uploadify.com/demos/
http://www.zamzar.com/
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
Hey, that's mine from somewhere :).
In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).
So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.
If not, you could try to jump to it by pressing Alt + N, at least on Windows...
If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:
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);
It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).
For Flash, the only alternative I know (from this discussion) is to use the dark technique:
First, you modify the source code of you the flash application, exposing
internal methods using the ActionScript's ExternalInterface API.
Once exposed, these methods will be callable by JavaScript in the browser.
Second, now that JavaScript can call internal methods in your flash app,
you use WebDriver to make a JavaScript call in the web page, which will
then call into your flash app.
This technique is explained further in the docs of the flash-selenium project.
(http://code.google.com/p/flash-selenium/), but the idea behind the technique
applies just as well to WebDriver.
Below code works for me :
public void test() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.freepdfconvert.com/pdf-word");
driver.findElement(By.id("clientUpload")).click();
driver.switchTo()
.activeElement()
.sendKeys(
"/home/likewise-open/GLOBAL/123/Documents/filename.txt");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("convertButton"));
Using C# and Selenium this code here works for me, NOTE you will want to use a parameter to swap out "localhost" in the FindWindow call for your particular server if it is not localhost and tracking which is the newest dialog open if there is more than one dialog hanging around, but this should get you started:
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using OpenQA.Selenium;
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public static void UploadFile(this IWebDriver webDriver, string fileName)
{
webDriver.FindElement(By.Id("SWFUpload_0")).Click();
var dialogHWnd = FindWindow(null, "Select file(s) to upload by localhost");
var setFocus = SetForegroundWindow(dialogHWnd);
if (setFocus)
{
Thread.Sleep(500);
SendKeys.SendWait(fileName);
SendKeys.SendWait("{ENTER}");
}
}
I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"
Below is the selenium code line to run this vbs file,
driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );
Find the element (must be an input element with type="file" attribute) and send the path to the file.
WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");
NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector
WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");
There is a simpler way to solve this then what Slanec described. Hes solution works when you are using an English keyboard, if not you will have a hard time trying to "map" the key for special characters.
Instead of robot.keyPress and robot.keyRelease every single key you can use Toolkit to copy the String to the clipboard and then paste it.
StringSelection s = new StringSelection("Path to the file");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
Robot robot = new Robot();
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
robot.keyPress(java.awt.event.KeyEvent.VK_V);
robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
Thread.sleep(3000);
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
First add the file to your project resource directory
then
public YourPage uploadFileBtnSendKeys() {
final ClassLoader classLoader = getClass().getClassLoader();
final File file = new File(classLoader.getResource("yourFile.whatever").getPath());
uploadFileBtn.sendKeys(file.getPath());
return this;
}
Walla, you will see your choosen selected file, and have skipped the file explorer window
Import System.Windows.Forms binary to the test solution and call the following two LOC on clicking the Upload button on the UI.
// Send the file path and enter file path and wait.
System.Windows.Forms.SendKeys.SendWait("complete path of the file");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
An alternative solution would be to write a script to automate the Open File dialog. See AutoIt.
Also, if you can't "click" the element, my workaround is generally to do this:
element.SendKeys(Keys.Enter);
Hope this helps (Even though it's an old post)
Below code works for me:
// wait for the window to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
// switch to the file upload window
Alert alert = driver.switchTo().alert();
// enter the filename
alert.sendKeys(fileName);
// hit enter
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
// switch back
driver.switchTo().activeElement();
You have put double slash \\ for the entire absolute path to achieve this
Example:- D:\\images\\Lighthouse.jpg
Steps
- use sendkeys for the button having browse option(The button which will open
your window box to select files)
- Now click on the button which is going to upload you file
driver.findElement(By.xpath("//input[#id='files']")).sendKeys("D:\\images\\Lighthouse.jpg");
Thread.sleep(5000);
driver.findElement(By.xpath("//button[#id='Upload']")).click();
Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.
Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
Please use below link for further assistance:
http://www.guru99.com/use-autoit-selenium.html
webDriver.FindElement(By.CssSelector("--cssSelector--")).Click();
webDriver.SwitchTo().ActiveElement().SendKeys(fileName);
worked well for me. Taking another approach provided in answer above by Matt in C# .net could also work with Class name #32770 for upload box.
The below one had worked for me
webDriver.findElement(By.xpath("//input[#type='file' and #name='importFile']")).sendKeys("C:/path/to/file.jpg");
Double the backslashes in the path, like this:
driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");

Categories