Automatic Closing of Web Browser in Selenium - java

I am currently trying to re-run an old Selenium test. It was working as intended previously but now when I try to run it, I get an error. Here is the following code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class IMDBSearch {
public static void main(String[] args)
{
//new driver for chrome
WebDriver driver = new ChromeDriver();
//entering the url
String url = "http://www.imdb.com/search/title";
driver.get(url);
//clicking the featured film radio button
WebElement featureFilm = driver.findElement(By.id("title_type-1"));
featureFilm.click();
//clicking the tvmovie radio button
WebElement tvMovie = driver.findElement(By.id("title_type-2"));
tvMovie.click();
//clicking the tv radio button
WebElement tvButton = driver.findElement(By.id("title_type-3"));
tvButton.click();
//using the xpath to select a 7.0 minimum rating
WebElement userRating = driver.findElement(By.xpath("//body//div[#id='main']//div/select[#name='user_rating-min']/option[text()= '7.0']"));
userRating.click();
//using xpath to select US as a country
WebElement country = driver.findElement(By.xpath("//body//div[#id='main']//div/select[#class = 'countries']/option[#value= 'us']"));
country.click();
//using xpath to select the sorting by user rating
WebElement sort = driver.findElement(By.xpath("//body//div[#id= 'main']//div/select[#name = 'sort']/option[#value = 'user_rating,asc']"));
sort.click();
//using xpath to click on the search button
WebElement searchButton = driver.findElement(By.xpath("//div[#id= 'main']/p/button[text()= 'Search']"));
searchButton.click();
//using xpath to get the first movie from the list
//displaying the first movie from the list
WebElement firstTitle = driver.findElement(By.xpath("//div[#id = 'main']//h3/span[text()= '1.']/following-sibling::a"));
String title = firstTitle.getText();
System.out.println("1. " + title);
//using xpath to get the second movie from the list
//displaying the second movie from the list
WebElement secondTitle = driver.findElement(By.xpath("//div[#id = 'main']//h3/span[text()= '2.']/following-sibling::a"));
String title2 = secondTitle.getText();
System.out.println("2. " + title2);
//using xpath to get the third movie from the list
//displaying the third movie from the list
WebElement thirdTitle = driver.findElement(By.xpath("//div[#id = 'main']//h3/span[text()= '3.']/following-sibling::a"));
String title3 = thirdTitle.getText();
System.out.println("3. " + title3);
//using xpath to get the fourth movie from the list
//displaying the fourth movie from the list
WebElement fourthTitle = driver.findElement(By.xpath("//div[#id = 'main']//h3/span[text()= '4.']/following-sibling::a"));
String title4 = fourthTitle.getText();
System.out.println("4. " + title4);
//using xpath to get the fifth movie from the list
//displaying the fifth movie from the list
WebElement fifthTitle = driver.findElement(By.xpath("//div[#id = 'main']//h3/span[text()= '5.']/following-sibling::a"));
String title5 = fifthTitle.getText();
System.out.println("5. " + title5);
}
While I know this was working previously, it has been shooting me this error:
Starting ChromeDriver 2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129) on port 20969
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: session not created exception
from unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData": {"frameId":"3940.1","isDefault":true},"id":1,"name":"","origin":"://"}
(Session info: chrome=55.0.2883.87)
(Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 2.14 seconds
Build info: version: '3.0.0-beta2', revision: '2aa21c1', time: '2016-08-02 15:03:28 -0700'
System info: host: 'Qualitest-PC', ip: '192.168.2.106', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_101'
Driver info: org.openqa.selenium.chrome.ChromeDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
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:683)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:247)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:143)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:159)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
at PracticeClass.main(PracticeClass.java:10)

You should try updating your chromedriver version. The version you are using (v2.23) is only specified for v51-53 and you are using Chrome 55. Try with the latest chromedriver v2.27

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());

Android Appium Chrome Button Does not clicks or Taps?

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.

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

Selenium NoSuchElementException while trying to find an element

I am having an issue with Selenium targeting a username and password textbox. My main goal is to have my program open Chrome browser, load isis.ufl.edu, proceed to registration, then sign on with the user's username and password. The problem is that when I give an xpath or css path to target the username and password textbox, Eclipse gives me a error stating it cant find the element. Some say this only occurs with Chrome but does anyone know a way around this?
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element
(Session info: chrome=40.0.2214.115)
(Driver info: chromedriver=2.14.313457 (3d645c400edf2e2c500566c9aa096063e707c9cf),platform=Mac OS X 10.10.2 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 23 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
System info: host: 'Dailens-MacBook-Pro.local', ip: '192.168.1.102', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.2', java.version: '1.7.0_67'
Session ID: c8b9c346dcf7bcdc28c1cc078638d872
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=/var/folders/81/v5g4vbfj05x16pgjg9h7_kf40000gn/T/.org.chromium.Chromium.ML2rMj}, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=40.0.2214.115, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]
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:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:441)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:426)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at TestClass.main(TestClass.java:51)
Here is my code :
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.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.Scanner;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class TestClass {
public static void main(String[] args) {
//Fetching isis and schedule information
Scanner user_input = new Scanner(System.in);
System.out.println("User enter Isis username:");
System.out.println("User enter Isis password:");
System.out.println("User enter current semester:");
String username = user_input.next();
String password = user_input.next();
String semester = user_input.next();
// Create a new instance of the chrome driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
System.setProperty("webdriver.chrome.driver", "//users/dailenspencer/downloads/chromedriver");
WebDriver driver = new ChromeDriver();
// And now use this to visit isis
driver.get("http://www.isis.ufl.edu/");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.isis.ufl.edu/");
//Clicking on registration tab
driver.findElement(By.xpath("//a[#class='hideToggle2']")).click();
//If user input fall for semester, click on fall registration
if(semester.charAt(0) == 'f' || semester.charAt(0) == 'F'){
driver.findElement(By.cssSelector("#reg > ul:nth-child(3) > li:nth-child(3) > a")).click();
}
//If user input summer, click on summer registration tab
if(semester.charAt(1) == 'u'){
driver.findElement(By.cssSelector("#reg > ul:nth-child(3) > li:nth-child(2) > a")).click();
}
//else, click spring registration tab
else{
driver.findElement(By.cssSelector("#reg > ul:nth-child(3) > li:nth-child(1) > a")).click();
}
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
WebElement resultsDiv = driver.findElement(By.className("wrap"));
// If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
//Find the textbox for username, and send username to text box
WebElement elementu = driver.findElement(By.cssSelector("#username"));
elementu.sendKeys(username);
WebElement elementp = driver.findElement(By.cssSelector("#password"));
elementp.sendKeys(password);
// Now submit the form. WebDriver will find the form for us from the element
driver.findElement(By.cssSelector("body > div.content > div > form > p:nth-child(3) > input")).click();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("isis");
}
});
//Close the browser
driver.quit();
}
}
You need to explicitly wait for elements to become visible before interacting with them, example for the "Transcripts" link:
WebDriverWait wait = new WebDriverWait(webDriver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#class='hideToggle2']")));
Also, it looks like it is failing while trying to find the Summer registration link. I'd find it by partial link text instead of diving into CSS selectors:
driver.findElement(By.partialLinkText("Summer")).click();

Categories

Resources