Java Robot keyPress crazy behavior - java

try {
Robot robot = new Robot();
1 robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
2 robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
3 robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
} catch (AWTException e) {
e.printStackTrace();
}
See the above code, I was trying to enter some text into IE browser tag, however I got weird message saying " left hand side of an assignment must be a variable" while debugging into the robot.keyPress line, & eclipse automatically put a number in the front of the line, ie: 1,2,3 instances above.
Any idea? Is it the the web site tag has some tricky security enforce?
Thanks

While in debug mode, the focus was on Eclipse itself, that's why I saw this weird behavior.

Related

How can I detect an element on the screen because sometimes it come with different formats using selenium java?

I am trying to detect an element that can have different index on the screen, sometimes it can be detected like this (//input[#value='OK'])[1] and sometimes it appears and can be detected with this (//input[#value='OK'])[2] there is no other way to get this element to be unique because multiple elements are developed the same but every time it will appear with a different format, is there anyway to check whether it's detected by 1st or the 2nd index and then press on it. I tried try and catch but it's not working
try{
while(true) {
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOf(driver.findElement(element))))
.click();
}
} catch (Exception ignored){ }
Just Try this
if(driver.findElements(By.xpath("xpath1")).size()!=0)
{
driver.findElement(By.xpath("xpath1")).click
}
else if(driver.findElements(By.xpath("xpath2")).size()!=0)
{
driver.findElement(By.xpath("xpath2")).click
}
Investigate to see if you can write relative xpath that is valid for both scenarios. Failing you can use an xpath conditional operator to combine the two values like //*[#id='notify-containe' or contains(#id,'notify-container')].

Selenium WebDriver Java - how to perform "if exists, then click, else skip"?

On my page, I have alerts that display sometimes. (these are actually notifications in Salesforce) These alerts break my scripts since my scripts can't find the elements behind the alerts. I'd like to check for the alerts and if they exist, dismiss them. If they don't exist, then move on to the next step.
Secondary problem is that there may be more than one of these alerts. So it may have dismiss anywhere from 1 to 6 or more alerts.
I've added this code to my test script and it works if there is ONE alert. Obviously my script fails if there is more than one alert or if there are zero alerts.
driver.findElement(By.xpath("//button[contains(#title,'Dismiss notification')]")).click();
I'm still learning java, so please be gentle. ;) But I'd love to put this into a method so it can look for those buttons, click if they exist, keep looking for more until it finds none, then move on. I just have no idea how to do it.
I'm using TestNG too, I know that makes a difference in what's allowable and what's not.
Thank you!
You can use wait with try/catch to get all buttons and click on each if exist.
1.If alerts all appear at once use code below:
try{
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.cssSelector("button[title*='Dismiss notification']"))))
.forEach(WebElement::click);
} catch (Exception ignored){ }
2.If alerts appear singly use code below:
try{
while(true) {
new WebDriverWait(driver, 5)
.ignoring(ElementNotVisibleException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("button[title*='Dismiss notification']"))))
.click();
}
} catch (Exception ignored){ }
Use findElements which will return a list of 0 if the element does not exist.
E.G:
List<WebElement> x = driver.findElements(By.xpath("//button[contains(#title,'Dismiss notification')]"));
if (x.size() > 0)
{
x.get(0).click();
}
// else element is not found.
findElements will return the list no need of creating one again. Also x.size() won't work because list object has no attribute size so we have to check the length. No need of using x.get(0).click();.
driver.click(By.xpath("//button[contains(#title,'Dismiss notification')]")) should work.
x = driver.findElements(By.xpath("//button[contains(#title,'Dismiss notification')]"));
if (len(x) > 0) {
x.click();
}

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)

Java bot using the Robot class

I'm trying to create a game bot using the Robot class.
I have tried the following code to perform a right click of the mouse:
robot.mousePress(InputEvent.BUTTON3_MASK);
robot.mouseRelease(InputEvent.BUTTON3_MASK);
And it worked.
I'm testing it on a client side 3d online game.
Pressing the key "1" should perform some kind of a movement ingame, and when I tried the following code it didn't worked:
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
But it did worked when I used that code while speaking in the chat in game.
It's been tested over and over and I keep getting the same result.
Is it something that I have done wrong?or somehow the game detect that I'm not the one that pressing that key.
You are probably releasing the key too quickly. Try sleeping for 30~60ms before releasing the key:
robot.keyPress(KeyEvent.VK_1);
try {
Thread.sleep(50);
} catch(Exception e) {
e.printStackTrace();
}
robot.keyRelease(KeyEvent.VK_1);

Applet issue with jre 1.6

I have an applet, and it consist of an CLOSE button which closes the applet and redirects user to the home page. Home page consists 3 frames (Top, Left and Right). Once user clicks on the CLOSE button, the home page is appearing in the right frames, due to this now user has inconsistent view (multiple frames) of the page.
Code written in CLOSE button of the applet.
protected void cancelActionPerformed()
{
try
{
String type = "3";
AppletContext context = getAppletContext();
context.showDocument(new URL("javascript:goBack(\"" + type + "\")"));
destroy();
}
catch(MalformedURLException ex)
{
// System.out.println(ex.getMessage());
}
}
This is working perfectly in the JRE version 1.6 UPDATES 07 installed in the browser but higher updates of JRE creating this problem.
Kindly suggest if any thing wrong or any suggestion to overcome this situation.
Thank you
Regards
By default the JRE does not support java.net.URLs with the javascript protocol. So unless a handler has been installed (even though you never use it - horrible API) you will get a java.net.MalformedURLException.
Probably the easiest solution is to use the LiveConnect API to call the JavaScript.

Categories