Android Appium Chrome Button Does not clicks or Taps? - java

I was able to click on links and texts but I cannot click on Button using Chrome with Android Appium
public void testcheck() {
System.out.println("Select");
//<a id="vivKo" href="javascript:void(0);" class="btn btn- green vivKo at_vivKo">
//<span class="text">vivKo</span>
// <i class="fa fa-chevron-right"></i> </a>
//driver.findElementByXPath("//span[contains(., \"" + vivKo + "\")]").click();
WebElement vova = (WebElement) driver.findElementByXPath("//*[#id=vivKo']");
TouchAction ta = new TouchAction(driver);
ta.longPress(vova);
//WebElement vova = (WebElement) driver.findElementByXPath("//*[#id='vivKo']");
driver.findElement(By.xpath("//*[#id='vivKo']")).click();
WebElement elementToClick = driver.findElement(By.xpath("//*[#id='vivKo']"));
Actions actions = new Actions(driver);
new WebDriverWait(driver, 60).until(ExpectedConditions.visibilityOf(vova));
actions.moveToElement(elementToClick).click().build().perform();
Error: FAILED: testcheck
org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (180, 630)
(Session info: chrome=62.0.3202.84)
(Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.12.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 237 milliseconds
Build info: version: '2.52.0', revision: '4c2593cfc3689a7fcd7be52549167e5ccc93ad28', time: '2016-02-11 11:22:43'
System info: host: 'AMAC02T90QRGTFM', ip: '192.168.14.180', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{deviceScreenSize=1440x2960, networkConnectionEnabled=true, warnings={}, databaseEnabled=false, deviceName=9887fc35525a485333, platform=LINUX, deviceUDID=9887fc35525a485333, desired={platformVersion=7.0, browserName=Chrome, platformName=Android, deviceName=Vovchik}, platformVersion=7.0, webStorageEnabled=false, locationContextEnabled=false, takesScreenshot=true, browserName=Chrome, javascriptEnabled=true, deviceModel=SM-G950U, platformName=Android, deviceManufacturer=samsung}]
Session ID: 10923751-6fb6-48d1-b61d-50be29f84770
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at

If you know there is an element that not displayed on screen but still possible to get it via driver, you can swipe up (e.g. 100 px) before you try to click it.
int x = element.getLocation().getX();
int y = element.getLocation().getY();
new TouchAction(driver)
.press(x, y)
.waitAction(ofMillis(500))
.moveTo(x, y+100)
.release()
.perform();
Of course, you can calculate more accurate px shift taking in account screen size.

Related

Selenium Opening Video on youtube & finding duration/time-elapsed

The following code opens an internet explorer, goes to the website youtube.com, opens a video, searches for a webelement (with id movie_player), hovers over the mouse to go to the center of webelement (ie: middle of youtube video screen so that the duration tab is visible), then tries to fetch the value of total duration and duration elapsed.
The problem seems to be that its not able to find the web element for current time as it seems the mouse hovering action does not happen as expected.
How to achieve the mouse hovering correctly?
WebDriver driver4 = new InternetExplorerDriver();
driver4.get("https://www.youtube.com");
String[] arr = {"saiyoni saiyoni song video","bulla ki jaana main kaun video song"};
WebDriverWait wait7 = new WebDriverWait(driver4,30);
WebElement textBox2 = wait7.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[id=masthead-search-term]")));
textBox2.sendKeys(arr[0]);
wait7.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[#id='search-btn']"))).click();
WebElement we0 = wait7.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#href='/watch?v=0GLYKYgSE0Y']")));
we0.click();
Actions builder = new Actions(driver4);
WebElement we = driver4.findElement(By.id("movie_player"));
Action mouseMovement=builder.moveToElement(we).build();
mouseMovement.perform();
WebElement currentTime = wait9.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[#class='ytp-time-current']")));
WebElement durationTime= wait9.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[#class='ytp-time-duration']")));
Error:
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //span[#class='ytp-time-duration'] (tried for 30 second(s) with 500 MILLISECONDS interval)
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.5', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{acceptInsecureCerts=false, browserVersion=11, se:ieOptions={nativeEvents=true, browserAttachTimeout=0, ie.ensureCleanSession=false, elementScrollBehavior=0, enablePersistentHover=true, ie.browserCommandLineSwitches=, ie.forceCreateProcessApi=false, requireWindowFocus=false, initialBrowserUrl=http://localhost:5514/, ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000, ignoreProtectedModeSettings=false}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, platform=WINDOWS}]
Session ID: 84b0b0b5-af27-4208-82bb-599d9ffa2552
at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:82)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:231)
at packageFF.browserAutomation.main(browserAutomation.java:116)
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.wonderplugin.com/wordpress-lightbox");
WebElement element=driver.findElement(By.xpath("//a[contains(text(),'Open a Div in Lightbox')]"));
element.click();
System.out.println("found element and clicked");
Thread.sleep(3000);
WebElement frameElement=driver.findElement(By.xpath("//iframe[#src='https://www.youtube.com/embed/wswxQ3mhwqQ']"));
driver.switchTo().frame(frameElement);
driver.findElement(By.xpath("//button[#aria-label=\'Play\']")).click();
Actions builder = new Actions(driver);
WebElement we = driver.findElement(By.className("ytp-progress-bar-container"));
Action mouseMovement=builder.moveToElement(we).build();
mouseMovement.perform();
we.click();
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement titleText=wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("ytp-title-link")));
System.out.println(titleText.getText());
WebElement time=wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span.ytp-time-current")));
System.out.println(time.getText());

Selenium Webdriver - element not clickable error in firefox

The element not clickable error that usually appears in chrome driver happens to be showing in firefox also. The error message shown:
Exception in thread "main" org.openqa.selenium.WebDriverException: Element is not clickable at point (141, 299.29998779296875). Other element would receive the click: <div class="showOnTop" id="loadingPanelContainer"></div>
Command duration or timeout: 209 milliseconds
Build info: version: '2.51.0', revision: '1af067dbcaedd7d2ab9af5151fc471d363d97193', time: '2016-02-05 11:20:57'
System info: host: 'Bhaveen-ThinkPad', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'i386', os.version: '3.13.0-77-generic', java.version: '1.7.0_95'
Session ID: 08e0d738-b946-4886-a179-9659d44b717b
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=LINUX, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=44.0.2}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:327)
at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:85)
at config.KeyActions.handleLeftMenu(KeyActions.java:479)
at scripts.Vital_Data_Script.setVitalData(Vital_Data_Script.java:383)
at scripts.Vital_Data_Script.executeActions(Vital_Data_Script.java:95)
at scripts.Vital_Data_Script.executeTestCase(Vital_Data_Script.java:60)
at scripts.Vital_Data_Script.main(Vital_Data_Script.java:31)
You should probably wait for the element to be clickable, You can use:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.<your locator>));
OR Sometimes you will even need to hover over the element to make it clickable. This you can do by this:
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) driver).executeScript(mouseOverScript,
driver.findElement(By.<your locator>));
After doing this you can try :
Normal click() function:
driver.findElement(By.<your locator>).click();
OR
Non-native javascript executor:
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", driver.findElement(By.<your locator>));
Prateek's answer is correct. However something I've noticed with the latest version of Firefox and Selenium 2.50.1 is that it's not always scrolling the element into view successfully.
If your problem is that the element is scrolled off the screen (and as a result under something like a header bar), you can try scrolling it back into view like this:
private void scrollToElementAndClick(WebElement element) {
int yScrollPosition = element.getLocation().getY();
js.executeScript("window.scroll(0, " + yScrollPosition + ");");
element.click();
}
if you need you could also add in a static offset (if for example you have a page header that is 200px high and always displayed):
public static final int HEADER_OFFSET = 200;
private void scrollToElementAndClick(WebElement element) {
int yScrollPosition = element.getLocation().getY() - HEADER-OFFSET;
js.executeScript("window.scroll(0, " + yScrollPosition + ");");
element.click();
}

Element cannot be found only trough Jenkins build

I have a problem with my Automated test,
My test is running without problems trough Eclipse.
But when i want to run this test on Jenkins, it always fail on the same line(on same selector).
Running TestSuite Starting ChromeDriver 2.21.371459
(36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4) on port 21173 Only local
connections are allowed. Tests run: 1, Failures: 1, Errors: 0,
Skipped: 0, Time elapsed: 34.563 sec <<< FAILURE! - in TestSuite
f(webdriver.Single_match_ticket) Time elapsed: 33.86 sec <<<
FAILURE! org.openqa.selenium.TimeoutException: Timed out after 19
seconds waiting for element to be clickable: By.cssSelector:
a[id='PopularOpener'] > span[tittle='All'] Build info: version:
'2.50.1', revision: 'd7fc91b29de65b790abb01f3ac5f7ea2191c88a7', time:
'2016-01-29 11:11:26' System info: host: 'Ivan-HP', ip:
'192.168.221.103', os.name: 'Windows 7', os.arch: 'amd64', os.version:
'6.1', java.version: '1.8.0_65' Driver info:
org.openqa.selenium.chrome.ChromeDriver Capabilities
[{applicationCacheEnabled=false, rotatable=false,
mobileEmulationEnabled=false, chrome={chromedriverVersion=2.21.371459
(36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),
userDataDir=C:\Windows\TEMP\scoped_dir676_8604},
takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true,
hasTouchScreen=false, version=48.0.2564.97, platform=XP,
browserConnectionEnabled=false, nativeEvents=true,
acceptSslCerts=true, locationContextEnabled=true,
webStorageEnabled=true, browserName=chrome, takesScreenshot=true,
javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID:
634bd38ceca35f9fabe19d967ad5d847 at
webdriver.Single_match_ticket.f(Single_match_ticket.java:85)
Results :
Failed tests: Single_match_ticket.f:85 ยป Timeout Timed out after 19
seconds waiting for elem...
Here is part of my code:
public void f() throws Exception {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "webdriver\\chromedriver.exe");
// open Google Chrome
driver = new ChromeDriver();
// Maximize window
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
WebDriverWait wait = new WebDriverWait(driver, 19);
driver.navigate().to("TESTED SITE");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[name='username']")));
// Set values for username and pass
driver.findElement(By.cssSelector("input[name='username']")).sendKeys("1testuser");
driver.findElement(By.cssSelector("input[name='password']")).sendKeys("testtest");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button[type='submit']")));
// Click on LogIn button
driver.findElement(By.cssSelector("button[type='submit']")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='userName']")));
String Username = driver.findElement(By.xpath(".//*[#id='userName']")).getText();
String Username1 = "1testuser";
if (!Username1.equals(Username)) {
throw new Exception("You are not logged in");
} else {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.logout-btn.balance.visible")));
String Balance = driver.findElement(By.cssSelector("div.logout-btn.balance.visible")).getText();
String[] parts = Balance.split("\\.");
String part1 = parts[0];
String secondpart = "";
if (part1.contains(",")) {
secondpart = part1.replace(",", "");
} else {
secondpart = part1;
}
int BalanceInt = Integer.parseInt(secondpart);
if (BalanceInt > 200) {
wait.until(ExpectedConditions
.visibilityOfElementLocated(By.cssSelector("a[id='PopularOpener'] > span[title='All']")));
driver.findElement((By.cssSelector("a[id='PopularOpener'] > span[title='All']"))).click();
for (int i = 0; i < 3; i++) {
the test fail on this line:
wait.until(ExpectedConditions
.visibilityOfElementLocated(By.cssSelector("a[id='PopularOpener'] > span[title='All']")));
try to select this element not by css as you do
By.cssSelector("a[id='PopularOpener'] > span[title='All']"
select it by something else for example id, name, xpath.
Or if it fails only through Jenkins, check the difference Your local machine from the machine you run the test through Jenkins.
Check java version, chrome driver, OS version etc.
I resolve this issue with JavascriptExecutor.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("Categories.readPopular()");
This function works fine on J

findElements() returns NoSuchElementException instead of returning empty list

Following is code :
List<WebElement> listOfAllMatchingElements = driver.findElements(By.xpath(".//*[#id='e1MMenuRoot']/div/div[last()]"))
OR
List<WebElement> listOfAllMatchingElements = driver.findElements(By.xpath(".//*[#id='e1MMenuRoot']/div/div[5]"))
Now as per my understanding, this should return list of Web elements Or an empty list[Considering the xpath is syntactically correct].
Instead, an exception[NoSuchElementException] is thrown with a confusing message as "returned an unexpected error".
Following is the exception,
org.openqa.selenium.NoSuchElementException: Finding elements with xpath == .//*[#id='e1MMenuRoot']/div/div[5]returned an unexpected error (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.37 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:17:10'
System info: host: 'OTINWISRCDT050', ip: '172.24.187.38', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_71'
*** Element info: {Using=xpath, value=.//*[#id='e1MMenuRoot']/div/div[5]}
Session ID: a45d6015-f529-4e85-924e-3214076d59e8
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true, ie.ensureCleanSession=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=9, ie.usePerProcessProxy=false, ignoreProtectedModeSettings=true, cssSelectorsEnabled=true, requireWindowFocus=false, initialBrowserUrl=http://localhost:31736/, handlesAlerts=true, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}]
The code used for element wait is like,
public boolean customElementWaitWithTimeoutWithProperties(WebDriver UtilDriver,By locatorWithLocation,int Timeout)
{
WebDriver driver = UtilDriver;
boolean elementFound=false;
int i=1;
try
{
while(i<=Timeout )
{
if(((Boolean.compare(elementFound,false)))==0)
{
List<WebElement> listOfAllMatchingElements = driver.findElements(locatorWithLocation);
if(!(listOfAllMatchingElements.isEmpty()) && (((Boolean.compare(elementFound,false)))==0))
{
if(listOfAllMatchingElements.size()>1)
{
log.info("Common Methods :customElementWaitWithTimeout: More than one element is found for given location, check the location !!");
elementFound=false;
break;
}
else if(listOfAllMatchingElements.size()==1 && (((Boolean.compare(elementFound,false)))==0))
{
log.info("Common Methods :customElementWaitWithTimeout: Element found on "+i+" attempt !!");
elementFound=true;
break;
}
}
else if ((listOfAllMatchingElements.isEmpty()))
{
log.info("Common Methods :customElementWaitWithTimeout: Element is not found on "+i+" attempt!!");
}
Thread.sleep(1200);
}
i=i+1;
}
}
catch(Exception elementFoundCheck)
{
log.error("Common Methods[customElementWaitWithTimeout]: Exception caught !!");
elementFoundCheck.printStackTrace();
}
return elementFound;
}
[Additional info]However,
when i put a hard wait for certain time[To make sure element is loaded] & write as
driver.findElement(By.xpath(".//*[#id='e1MMenuRoot']/div/div[5]")).click();
The element is getting clicked.
Any reason/solution for the problem ??[findElements() returning NoSuchElementException]
Update
Why are you reinventing the wheel by writing your own wait algorithm when it's already there. Refer
//wait for 20 seconds
WebDriverWait wait = new WebDriverWait(driver, 20);
List<WebElement> listOfAllMatchingElements=wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(".//*[#id='e1MMenuRoot']/div/div[last()]")));

Error messge using selenium method 'isTextPresent'

I am trying to search for a string on some site using Selenium (2.32) method "isTextPresent".
I order to do it efficently I need to search it case insensitive as suggested with regexpi but I get an error as following (HTML contains the string "WHAT YOU SAY"):
Declaration:
private Selenium selenium;
driver = new FirefoxDriver();
String baseUrl = "http://openurl.ebscohost.com";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
Option 1 ("'SAY' in uppercase"):
if(selenium.isTextPresent("WHAT YOU SAY")) {
return ("PASS");
}
else{ return "FAIL";}
Output: "PASS"
Option 2 ("'SAy' with lower case leter"):
if(selenium.isTextPresent("WHAT YOU SAy")) {
return ("PASS");
}
else{ return "FAIL";}
Output: "FAIL"
Option 3 ("'SAy' with lower case letter but with regexp"):
if(selenium.isTextPresent("regexp:WHAT YOU SAy")) {
return ("PASS");
}
else{ return "FAIL";}
Output: "FAIL"
Option 4 ("'Say' with lower case letter but with regexpi"):
if(selenium.isTextPresent("regexpi:WHAT YOU SAy")) {
return ("PASS");
}
else{ return "FAIL";}
Output: ERROR
The error:
> ERROR:com.thoughtworks.selenium.SeleniumException: TypeError: RegExp(...).text is not a function
Command duration or timeout: 1.97 seconds
Build info: version: '2.32.0', revision: '6c40c18', time: '2013-04-09 17:23:22'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.6.0_32'
Session ID: 195d399d-c745-42c5-be6d-7d47811c9c26
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=firefox, rotatable=false, locationContextEnabled=true, version=20.0.1, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=true, nativeEvents=true, webStorageEnabled=true, applicationCacheEnabled=true, takesScreenshot=true}]
Have I missed something?
Thanks I advance!

Categories

Resources