I have some methods that are used to wait for an element to display, and in the try/catch for these methods, the catch is:
throw new ElementNotVisibleException()
I'm upgrading from Selenium 2.53 to Selenium 4, and ElementNotVisibleException() seems to not be available in Selenium 4. What should I replace it with? Is ElementNotInteractableException a suitable replacement?
Since release 4.1.3, the method ElementNotVisibleException() has been removed from selenium/java/src/org/openqa/selenium
See v4.1.2, where the classes ElementNotVisibleException & ElementNotSelectableException exist.
See v4.1.3, where the aforementioned classes have been removed.
This is due to the following:
Selenium 4 is more strict regarding W3C WebDriver, and W3C WebDriver has nothing to say about visibility at this point. If an element is not visible, the driver in W3C mode should return a ElementNotInteractableException
So methods using the ElementNotVisibleException.java class will have to be updated to use ElementNotInteractableException.java
Confirmation here: [🐛 Bug]: ElementNotVisibleException class is not found in selenium 4.1.3. Getting compilation issues saying ElementNotVisibleException not found
#10538
Example:
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public void selectUpload(String uploadType) throws Exception {
WebElement dropdown = driver.findElement(By.xpath("//select[contains(#name,'uploadFileResultsInput')]"));
int timeout = 0;
Exception finalException = null;
while (timeout < 5000) {
try {
new Select(dropdown).selectByVisibleText(uploadType);
return;
} catch (ElementNotVisibleException e) {
finalException = e;
}
Thread.sleep(500);
timeout += 500;
}
throw finalException;
}
to
import org.openqa.selenium.ElementNotInteractableException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public void selectUpload(String uploadType) throws Exception {
WebElement dropdown = driver.findElement(By.xpath("//select[contains(#name,'uploadFileResultsInput')]"));
int timeout = 0;
Exception finalException = null;
while (timeout < 5000) {
try {
new Select(dropdown).selectByVisibleText(uploadType);
return;
} catch (ElementNotInteractableException e) {
finalException = e;
}
Thread.sleep(500);
timeout += 500;
}
throw finalException;
}
Related
I am trying to drag and drop using Selenium Java. It is clicking but not dropping it in the destination specified.
Code used for dragging and dropping:
WebElement drag= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[1]/div/vr-columns/div/vr-toolbox/div/div[3]"));
//Drop
WebElement Drop= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[2]/div/vr-columns/div/div[2]/div/vr-validator/div/div[1]/vr-datagrid/vr-datagridrows/div[1]/div/div[2]/div[1]"));
Actions actions= new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
If this is not working, please share URL or page source code.
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
public class DragAndDropTest extends WebDriverSetup {
public static void main (String[] args) {
WebDriver driver = startChromeDriver(); // standard driver setup just wrapped
driver.get("https://demoqa.com/droppable/");
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(draggable, droppable).build().perform();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
driver.quit();
}
}
First, you have to move to the element you want to drag. Besides, you can use chaining.
...(your codes are above)
actions.moveToElement(drag)
.clickAndHold()
.moveToElement(Drop)
.release(Drop).perform();
try {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(drag));
Actions actions = new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
} catch (Exception e) {
System.out.println("Error occurred while dragging and dropping: " + e.getMessage());
}
I have added code snippet for further clarity.
I am using java-selenium-testNG and trying to login to a website zoho.com with 3 accounts and verifying if success. I have looked through somewhat similar issues but haven't found a solution that works in my case.
I instantiate the ChromeDriver in #BeforeMethod. Then I login to the website with first account and close the browser in my #AfterMethod.
I have to re-instantiate the browser with Driver = new ChromeDriver to login back with a new account as the instance is closed or atleast that's the feeling it gives error that the session id doesn't exists.
My issue is only the last instance of the driver is getting closed as I have driver.quit in the #AfterTest method. The other two instances remain in memory.
I have also tried using the same instance without closing the browser but in such cases the login option is not available on that particular website and my subsequent tests fail.
here is the code below for further clarification
package uk.dev.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.util.concurrent.TimeUnit;
public class zohoLogin {
WebDriver driver=null;
String winHandleBefore;
#DataProvider(name ="testData")
public Object[][] loginPasswordData()
{
return new Object[][]{
{"xxx#gmail.com",new String ("somepassword")} ,
{"yyy#gmail.com",new String ("somepassword")},
{"zzz#gmail.com",new String ("somepassword")},
};
}
#Test ( dataProvider = "testData")
public void enterUserDetails(String userEmail, String userPassword) throws InterruptedException {
driver.findElement(By.xpath("//input[#id='login_id']")).sendKeys(userEmail);
System.out.println(("Running for Test data " + userEmail));
Thread.sleep(2000);
driver.findElement(By.xpath("//button[#id='nextbtn']")).click();
Thread.sleep(2000);
System.out.println("clicked on Next");
driver.findElement(By.xpath("//input[#id='password']")).sendKeys(userPassword);
System.out.println("Entered the password");
driver.findElement(By.xpath("//button[#id='nextbtn']//span[contains(text(),'Sign in')]")).click();
System.out.println("Clicked on Signin");
Thread.sleep(2000);
}
#BeforeMethod
public void loginZoho() throws InterruptedException
{
driver = new ChromeDriver();
driver.get("https://www.zoho.com");
System.out.println("Open the browser");
driver.findElement(By.xpath("//a[#class='zh-login']")).click();
//driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
Thread.sleep(5000);
}
#AfterMethod
public void closeBrosers() throws InterruptedException {
Thread.sleep(2000);
driver.close();
System.out.println("Close the browser");
}
#BeforeTest
public void setupBrowser()
{ WebDriverManager.chromedriver().setup();
}
#AfterTest
public void tearDown()
{
driver.quit();
}
}
Attached the run results where 2 chrome driver instance can be seen.Also note the AfterMethod is not getting executed.
enter image description here
I am using driver.quit() method in selenium but facing the same issue. I think issue is related to the latest version of chromedriver.
public static void CloseDriver()
{
if (Driver != null)
{
Driver.Quit();
Driver = null;
}
}
I even tried Driver.Kill() but it resulted in closing all the browsers.
I've written a code using Selenium WD and JUnit that should check if proper page is loaded and the table of this page is not null
Besides assertion, to make sure that proper page is loaded (checking if URL contains specified text), I've put "if-else" statement in "waitUntilPageLoaded" method.
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GuruSearch
{
#Test
static void checkDemoLogin()
{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pansa\\Documents\\Webdrivers\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 10);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(FirefoxDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The "if-else" statement in "waitUntilPageLoaded" method returns "OK", but TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"))
throws AssertionError, although the text appears in the page.
Why there is AssertionError thrown?
As you are using the JUnit annotations, the annotated method shouldn't be static. I have modified your code a bit, try the below:
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.TestCase;
public class GuruSearch
{
#Test
public void checkDemoLogin()
{
System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 30);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(WebDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The above code is printing 'OK' and Assert condition also passing. And I think, it doesn't matter if we give upper/lower case in the contains. It will match both the cases.
I don't have Firefox in my system so I have checked with Chrome, you change the browser and try... I hope it helps...
Requirement: Go to the link which is a job search for last 3 days.
1) Print job descriptions
2) Click on the next link to go to next page until you reach the last page
Problem: I am using try catch for no such element found for next link when I reach the last page. Using this solution it stops the script, by looking at the JUNIT bar you will not know if the test passed or failed.It is a grey bar since as I used exit. How can I make this code better so that I do not have to use that try catch and see a green bar for a passing test?
Code:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class QAJob {
#Test
public void jobSearch(){
WebDriver driver= new FirefoxDriver();
driver.get("https://www.indeed.com/jobs?as_and=qa+engineer&as_phr=&as_any=&as_not"
+ "=&as_ttl=&as_cmp=&jt=all&st=&salary=&radius=10&l=Bellevue%2C+WA&fromage=7&limit"
+ "=10&sort=date&psf=advsrch");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//code to scroll down to find the rest pages link
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,1000)", "");
// Find and print the number of pages for the search
List<WebElement> search_pages=driver.findElements(By.xpath("//div [contains(#class,'pagination')]//a"));
System.out.println("Number of pages found for this search " + search_pages.size());
while(search_pages.size()!=0){
List<WebElement> job_desc=driver.findElements(By.xpath("//div [contains(#id,'p')][contains(#class,'row')]"));
for(WebElement e:job_desc){
String str_job_desc=e.getText();
System.out.println(str_job_desc);
}
try
{
// closes the pop up that appears
driver.findElement(By.id("popover-x-button")).click();
}
catch (Exception e)
{
}
try
{
//click on next link to go to next page
driver.findElement(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]")).click();
//scroll down
JavascriptExecutor jse1 = (JavascriptExecutor) driver;
jse1.executeScript("window.scrollBy(0,1000)", "");
}
//when I get the exception(because no next link is available) exit.
catch (org.openqa.selenium.NoSuchElementException e)
{
System.exit(0);
}
}
}
}
Thanks in advance for your time and suggestion.
You can actually re-use the trick used in your code to avoid try-catch block
List<WebElement> popXButton=driver.findElements(By.id("popover-x-button"));
if (popXButton.size()>0){
driver.findElement(By.id("popover-x-button")).click();
}
Same extends to the next block too
List<WebElement> nextVal=driver.findElements(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]"));
if(nextVal.size()>0){
driver.findElement(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]")).click();
}
else{
break;//exits while loop!
}
I used SeleniumHQ to record my actions and then exported them to Java Unity WebDrive. Then I edited exported code and added many small extra things like looping over array, time-stamps, etc.
My code does following:
Log into my site.
Goto my profile.
Delete my previous announcement.
Post new announcement.
Log out.
I have tried using FirefoxDriver and HtmlUnitDriver, but every single of them gives me this weird problem. My code start doing its work and randomly stops in random spot and hangs there forever.
For example it could log in -> goto profile -> delete previous and then stop, or it could hang right in the login. I loop over those steps over and over again, and more I loop more likely it is to get stuck.
First loops success rate is 90% second loop is around 40% etc. Also which Driver I use also affects this. It is most likely to hang with HtmlUnitDriver and I would really want to use HtmlUnitDrive because I want to run my code headless on Ubuntu Server.
Has anyone else had similar problems?
EDIT : Now after many hours of testing, I noticed that its only HtmlUnitDriver that hangs and not Firefox. When using Firefox I can see what it is doing and it is doing everything as it should. Problem occurs with HtmlUnitDriver.
And here is the code itself:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class WebUpdater {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new HtmlUnitDriver(true); // JavaScript enabled.
baseUrl = "http://exampleurl.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUnity() throws Exception {
openAndLogin();
gotoProfile();
deletePreviousPost();
uploadPost();
logOut();
System.out.println("Done!");
}
private void openAndLogin() {
driver.get(baseUrl);
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("jsid-login-id")).clear();
driver.findElement(By.id("jsid-login-id")).sendKeys("bilgeis.babayan#gmail.com");
driver.findElement(By.id("jsid-login-password")).clear();
driver.findElement(By.id("jsid-login-password")).sendKeys("volume1991");
driver.findElement(By.cssSelector("input.right")).click();
}
private void gotoProfile() {
driver.findElement(By.cssSelector("img[alt=\"Profile\"]")).click();
}
private void deletePreviousPost() {
try {
driver.findElement(By.cssSelector("img[alt=\"ExampleName\"]")).click();
driver.findElement(By.linkText("Delete")).click();
assertTrue(closeAlertAndGetItsText().matches("^Confirm to delete this post[\\s\\S]$"));
} catch (Exception e) {
System.out.println(e);
}
}
private void uploadPost() {
driver.findElement(By.linkText("ExampleAction")).click();
driver.findElement(By.id("example_url")).clear();
driver.findElement(By.id("example_url")).sendKeys("Example text that gets typed in textfield.");
driver.findElement(By.cssSelector("input[name=\"example\"]")).clear();
driver.findElement(By.cssSelector("input[name=\"example\"]")).sendKeys("ExampleName");
driver.findElement(By.linkText("ExampleAction2")).click();
System.out.println("Done");
}
private void logOut() {
driver.get("http://exampleurl.com/logout");
System.out.println("Logged out.");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
in my main class I call WebUpdater class like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);
scan();
}
private static void scan() {
while (true) {
try {
// Test if connection is available and target url is up.
URL url = new URL("http://exampleurl.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
// Start tests.
WebUpdater updater = new WebUpdater();
updater.setUp();
updater.testUnity();
updater.tearDown();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
}
}
}
}
I had a bad experience with HtmlUnitDriver. Some time ago I wrote testing framework which were supposed to be fired at Hudson, and finally I decided to use Firefox driver which was more predictable and easier to debug. The point is that in my case it was a page full of javascripts - dynamically loaded fields, etc., and working with HtmlUnitDriver was really a can of worms.
If you really need to use HtmlUnitDriver try do debug 'pagesource' which is accessible for Selenium in 'current' (hanging) moment.
HtmlUnit 2.11 is flawed (see here and here), and since HtmlUnit 2.12 went live march 6th, the current version of HtmlUnitDriver is probably still based on HtmlUnit 2.11.
If you post your "http://exampleurl.com/" source code (or just give me a working url to the page if it's public) I could run the page with scripts through HtmlUnit 2.12.