I have trying trouble with trying to run Selenium in headless mode. I have using a find element for an out of stock button, when I run normal with the headless option commented out, I get expected behavior. When I run in headless, I get the wrong result. This is on the new Selenium beta for Java. (4.0) I'm using the beta because the old version does not have options to run Edge headless.
I have tried setting a duration, just takes longer to get the same wrong answer. And I have tried enabling the window size to full screen. No dice.
public class BestBuy extends Thread
{
public static void main(String[] args)
{
System.setProperty("webdriver.edge.driver", "Driver file path");
final EdgeOptions edgeOptions = new EdgeOptions();
//edgeOptions.addArguments("--headless");
WebDriver BestBuyDriver = new EdgeDriver(edgeOptions);
BestBuyDriver.get("https://www.bestbuy.com/site/dyson-airwrap-complete-styler-for-multiple-hair-types-and-styles-fuchsia-nickel/6284230.p?skuId=6284230");
try
{
List<WebElement> buttonText = BestBuyDriver.findElements(By.xpath("//button[text()='Sold Out']"));
List<WebElement> text = BestBuyDriver.findElements(By.xpath("//*[contains(text(),'Sold Out')]"));
//BestBuyDriver.findElement(By.className("btn-disabled"));
if(buttonText.size() > 0 || text.size() > 0)
System.out.println("Item out of stock");
else
System.out.println("Item in Stock");
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
System.out.println("Exception");
}
}
}
Related
I access Websites in a loop via selenium Java based. Some of the sites crash imediately so that i get the error
[1618982990.911][WARNING]: Timed out connecting to Chrome, retrying...
after a short time.
So this is not a selenium issue i assume, since even chrome crashes if i visit the site manually because of js errors, saying unresonsive Website
My problem is, that every time a site crashes, chromedriver and a chrome instance will stay alive so that i have high CPU usage after a short time.
Can i tell selenium to quit the instance if it is frozen? But i dont know how this should be possible if it does not get answer from chrome anymore?
Thankful for any solution or idea
Sometimes with some Windows version driver.quit() will not kill the chrome process which I have come across.
So at the end of the script you can kill the chrome processes if exists using java code, if the driver.quit doesn't work.
Please refer stackoverflow link which has the code to kill the process if exists in Java and pass the chrome process to it.
i found a workaround for anyone who would be interested. First setting up a pageLoadTimeout, after that force any chrome instance to be killed if an Exception is being thrown.
try{
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//some excecution code....
}
catch (Exception e) {
System.out.println("Error. Closing");
driver.quit();
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");}
timerChromeKillListener = new Timer();
timerChromeKillListener.schedule(new TimerTask()
{
#Override
public void run()
{
if (driver != null)
{
try
{
final Logs logs = driver.manage().logs();
final LogEntries driverLog = logs.get("driver");
if (driverLog != null)
{
final List<LogEntry> logEntries = driverLog.getAll();
for (final LogEntry logEntry : logEntries)
{
final String message = logEntry.getMessage();
if (message.contains("Unable to evaluate script: disconnected: not connected to DevTools") || message.contains("Timed out connecting to Chrome, retrying..."))
{
disconnect();
}
}
}
}
catch (Exception ignored)
{
}
}
}
} , 1 , 100);
I want to launch the selenium code on my mac.
With IntelliJ, I can launch each tests through the interface (thanks to the green button on the left).
I need now to launch selenium through cli, how to I do ?
My folder structure : /project/src/test/java/project_test/Tests.java
(I'm trying this right now : https://docs.seleniumhq.org/selenium-ide/docs/en/introduction/command-line-runner/, but as I have my driver inside my function I don't know if it will work, I'll let you know)
One example of my test :
public void TestA() throws InterruptedException, MessagingException {
String nameError = "TestA";
System.setProperty("webdriver.chrome.driver", locateDriver);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.navigate().to(url + "route");
Thread.sleep(3000);
driver.findElement(By.cssSelector(".primary > a[href=\""+url+"connexion/connexion/index/\"]")).click();
driver.findElement(By.id("login-client")).sendKeys("40003099");
driver.findElement(By.id("login-cp")).sendKeys("281101");
driver.findElement(By.xpath("//button[contains(text(),'Connexion')]")).click();
Thread.sleep(5000);
WebElement strvalue = driver.findElement(By.xpath("//*[#id=\"maincontent\"]/div[1]/div[2]/div/div/div"));
Thread.sleep(3000);
String expected = "some text";
String actual = strvalue.getText();
System.out.println(actual);
if(expected.equals(actual)){
System.out.println("Ok");
}
else {
System.out.println("Not ok");
sendMail(nameError);
}
Thread.sleep(5000);
driver.close();
}
Are you trying to run java file using external jar ? if yes, maybe this can help.
First, go to your directory :
cd project
MacBook-Pro: project$
Second, run this command :
java -cp .:yourFullPathExternalJar\*: src.test.java.project_test.Tests
Hope this helps
I am trying to write a Selenium test against Amazon site. I want to get "Sign in" element so that I can click on it.
url: www.amazon.es
Here is my Selenium Code:
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.amazon.es");
try
{
driver.findElement(By.id("nav-link-accountList")).click();
}
catch (Exception e)
{
System.out.println("Not Found");
}
Sometimes the code works correctly but sometimes it does not find the ID "nav-link-yourAccount". What is the problem? and how can I solve it?
Provide few seconds of wait, before click to this webelement so your driver may able to find the webelement.
For wait i am using Explicit wait method.
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("nav-link-accountList"))));
driver.findElement(By.id("nav-link-accountList")).click();
The element which you are trying to click with id as nav-link-yourAccount is not clickable. To proceed further you need to click either the link with text Hola. Identifícate or the link with text Mi cuenta using one of the following xpaths:
//a[#id='nav-link-yourAccount']/span[text()='Hola. Identifícate']
or
//a[#id="nav-link-yourAccount"]/span[contains(text(),'Mi cuenta')]
Instead using implicit wait try using explicit wait for the login element.
I've tried with explicit wait over 50 click and it did works.
Here is code you can use.
public class dump {
public static void main(String a[]){
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 15);
for(int i=0; i<=50; i++){
driver.get("https://www.amazon.es");
try{
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id='nav-link-accountList']")));
driver.findElement(By.xpath("//*[#id='nav-link-accountList']")).click();
System.out.println("clicked\t"+i);
}catch (Exception e){
e.printStackTrace();
System.out.println("Not Found");
}
}
}
}
Here is the proof of run:
All the best!!
Apply wait until element is appeared, so that it avoids NoSuchElementException and code is working without any error.
Below code is working fine:
driver.get("https://www.amazon.es");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement accontButton=driver.findElement(By.id("nav-link-accountList"));
WebDriverWait waitforelement=new WebDriverWait(driver,20);
waitforelement.until(ExpectedConditions.elementToBeClickable(accontButton));
try{
accontButton.click();
}
catch (Exception e){
System.out.println("Not Found");
}
Have you tried to find elements by xpath?
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.amazon.es");
try
{
driver.findElement(By.xpath("//*[#id='nav-link-accountList']")).click();
}catch (Exception e)
{
System.out.println("Not Found");
}
I'm working on Safari Browser and i got a problem.
"Unknown command: {"id":"5qhlf8uni92m","name":"mouseMoveTo","parameters":{"yoffset":25,"xoffset":10}}
(WARNING: The server did not provide any stacktrace information)"
How can i deal with this ?
NOTE: In my scenario, f book shows a notification pop-up and i can't select any element because when pop-up showed up, black screen appeared and i have to click anywhere to enable elements. That's why i used this code;
WebElement knownElement = null;
Actions builder = new Actions(driver);
builder.moveToElement(knownElement, 10, 25).click().build().perform();
In my opinion, it cause this problem. How can i change this code to fit in Safari ?
Please Refer this link : https://ynot408.wordpress.com/2011/09/22/drag-and-drop-using-selenium-webdriver/
OR :
public boolean onMouseOver(WebElement element){
boolean result = false;
try{
String mouseOverScript = "if(document.createEvent){
var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover',
true, false); arguments[0].dispatchEvent(evObj);
} else if(document.createEventObject){
arguments[0].fireEvent('onmouseover');}";
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(mouseOverScript, element);
result = true;
}catch (Exception e){
e.printStackTrace();
result = false;
}
return result;
}
I am evaluating tools for testing a WPF based app. I am currently trying Sikuli with the Java API. When I try to click on an object from Java code, the mouse cursor goes to the object and the object is highlighted, however the click action does not work, because the expected menu does not open. The click() method returns status 1 though.
If I am doing a click from Sikuli IDE, it works fine.
I tried 1.0.1 version and also the nightly build. Here's my code:
#Test
public void testLogin() {
Screen s = new Screen();
try {
s.wait(Constants.overflowMenu);
System.out.println(s.click(Constants.overflowMenu));
s.wait(Constants.signInMenuOption, 5);
} catch (FindFailed e) {
Assert.fail(e.getMessage());
}
}
What am I doing wrong?
try this code, it worked for me. what it does, it checks the image, click on it and then check this image again on the screen, if it still exists, click again.
Screen screen = new Screen();
Pattern pattern = null;
try
{
pattern = new Pattern(imageLocation);
screen.wait(pattern,30);
screen.click(pattern);
System.out.println("First Attempt To Find Image.");
}
catch(FindFailed f)
{
System.out.println("Exception In First Attempt: " +f.getMessage());
System.out.println("FindFailed Exception Handled By Method: ClickObjectUsingSikuli. Please check image being used to identify the webelement. supplied image: " +imageLocation);
Assert.fail("Image wasn't found. Please use correct image.");
}
Thread.sleep(1000);
//In case image/object wasn't clicked in first attempt and cursor stays in the same screen, then do second atempt.
if(screen.exists(pattern) != null)
{
try
{
screen.getLastMatch().click(pattern);
System.out.println("Second Attempt To Find Image.");
System.out.println("Object: " +imageLocation + " is clicked successfully.");
}
catch(FindFailed f)
{
System.out.println("Exception In Second Attempt: " +f.getMessage());
System.out.println("FindFailed Exception Handled By Method: ClickObjectUsingSikuli. Please check image being used to identify the webelement. supplied image: " +imageLocation);
}
}
In my case it seems it was a problem with the fact that I have two monitors..