Java Code Examples for org.openqa.selenium.WebDriver#getTitle()

The following examples show how to use org.openqa.selenium.WebDriver#getTitle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TransitionErrorException.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Build the message for this transition error exception.
 * 
 * @param context container context in which the error was detected
 * @param errorMessage error message
 * @return transition error exception message
 */
private static String buildMessage(ComponentContainer context, String errorMessage) {
    StringBuilder builder = new StringBuilder("Transition error detected: ").append(errorMessage);
    builder.append("\nContainer: ").append(Enhanceable.getContainerClass(context).getName());
    WebDriver driver = context.getWrappedDriver();
    if (driver != null) {
        String pageUrl = driver.getCurrentUrl();
        if (pageUrl != null) {
            builder.append("\nPage URL: ").append(pageUrl);
        }
        String pageTitle = driver.getTitle();
        if (pageTitle != null) {
            builder.append("\nPage title: ").append(pageTitle);
        }
    }
    return builder.toString();
}
 
Example 2
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * An expectation for checking the title of a page.
 *
 * @param title the expected title, which must be an exact match
 * @return true when the title matches, false otherwise
 */
public static ExpectedCondition<Boolean> titleIs(final String title) {
  return new ExpectedCondition<Boolean>() {
    private String currentTitle = "";

    @Override
    public Boolean apply(WebDriver driver) {
      currentTitle = driver.getTitle();
      return title.equals(currentTitle);
    }

    @Override
    public String toString() {
      return String.format("title to be \"%s\". Current title: \"%s\"", title, currentTitle);
    }
  };
}
 
Example 3
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * An expectation for checking that the title contains a case-sensitive substring
 *
 * @param title the fragment of title expected
 * @return true when the title matches, false otherwise
 */
public static ExpectedCondition<Boolean> titleContains(final String title) {
  return new ExpectedCondition<Boolean>() {
    private String currentTitle = "";

    @Override
    public Boolean apply(WebDriver driver) {
      currentTitle = driver.getTitle();
      return currentTitle != null && currentTitle.contains(title);
    }

    @Override
    public String toString() {
      return String.format("title to contain \"%s\". Current title: \"%s\"", title, currentTitle);
    }
  };
}
 
Example 4
Source File: StartTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToCreateAWebDriverBackedSeleniumInstance() {
  WebDriver driver = new FirefoxDriver();
  Selenium selenium = new WebDriverBackedSelenium(driver, root);

  try {
    selenium.open(env.getAppServer().whereIs("/"));

    String seleniumTitle = selenium.getTitle();
    String title = driver.getTitle();

    assertEquals(title, seleniumTitle);
  } finally {
    selenium.stop();
  }
}
 
Example 5
Source File: DriverHelper.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that page suites to expected pattern.
 * 
 * @param expectedPattern
 *            Expected Pattern
 * @return validation result.
 */
public boolean isTitleAsExpectedPattern(String expectedPattern) {
    boolean result;
    final String decryptedExpectedPattern = cryptoTool.decryptByPattern(expectedPattern, CRYPTO_PATTERN);
    WebDriver drv = getDriver();
    String actual = drv.getTitle();
    Pattern p = Pattern.compile(decryptedExpectedPattern);
    Matcher m = p.matcher(actual);
    if (m.find()) {
        Messager.TITLE_CORERECT.info(drv.getCurrentUrl(), actual);
        result = true;
    } else {
        Messager.TITLE_DOES_NOT_MATCH_TO_PATTERN.error(drv.getCurrentUrl(), expectedPattern, actual);
        result = false;
    }
    return result;
}
 
Example 6
Source File: GeckoDriverExample.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	//specify the location of GeckoDriver for Firefox browser automation
	System.setProperty("webdriver.gecko.driver", "geckodriver");
	WebDriver driver = new FirefoxDriver();
	driver.get("https://journaldev.com");
	String PageTitle = driver.getTitle();
	System.out.println("Page Title is:" + PageTitle);
	driver.close();
}
 
Example 7
Source File: PerformanceRemoteTest.java    From webdrivermanager-examples with Apache License 2.0 5 votes vote down vote up
private void singleTestExcution(WebDriver driver, int index) {
    driver.get("https://en.wikipedia.org/wiki/Main_Page");
    String title = driver.getTitle();
    assertTrue(title.equals("Wikipedia, the free encyclopedia"));

    SessionId sessionId = ((RemoteWebDriver) driver).getSessionId();
    System.out.println(index + " -- " + sessionId + " -- " + title);
}
 
Example 8
Source File: BaseGUI_IT.java    From movieapp-dialog with Apache License 2.0 5 votes vote down vote up
/**
 *<ul>
 *<li><B>Info: </B>Test the terms and conditions link on the landing page</li>
 *<li><B>Step: </B>Navigate to landing page</li>
 *<li><B>Verify: </B>Validate the terms and condition link is present</li>
 *<li><B>Step: </B>Select the terms and condition link</li>
 *<li><B>Verify: </B>Validate that the page navigated to title equals the expected title</li>
 *</ul>
 */
@Test
public void termsConditions() {

	RestAPI api = RestAPI.getAPI();	
	String expectedTitle = api.getJSONElem(COMMON, "terms");
	String title = "";
	
	Driver test = new Driver();
	WebDriver driver = test.getInstance();
       rule.setDriver(driver);
	
	MovieUI ui = test.getGui(driver);

	assertTrue("ERROR: Terms of service Link is not present",
				ui.fluentWaitPresent(MovieUI.termsServiceLink));
	
	logger.info("INFO: Select Terms and Conditions link");
	WebElement link = ui.findElement(MovieUI.termsServiceLink);
	link.click();

	title = driver.getTitle();
	
	logger.info("INFO: Title of Terms and Conditions page - " + title);
	
	//Validate that the title of page for Terms of Use matches expected
	assertTrue("ERROR: Title of page - " + title + " does not match expected title of the Terms and Conditions page - " + expectedTitle,
						title.contains(expectedTitle));
}
 
Example 9
Source File: BaseGUI_IT.java    From movieapp-dialog with Apache License 2.0 5 votes vote down vote up
/**
 *<ul>
 *<li><B>Info: </B>Test the privacy link on the landing page</li>
 *<li><B>Step: </B>Navigate to landing page</li>
 *<li><B>Verify: </B>Validate the privacy link is present</li>
 *<li><B>Step: </B>Select the privacy link</li>
 *<li><B>Verify: </B>Validate that the page navigated to title equals the expected title</li>
 *</ul>
 */
@Test
public void privacy() {

	RestAPI api = RestAPI.getAPI();	
	String expectedTitle = api.getJSONElem(COMMON, "privacy");
	String title = "";
	
	Driver test = new Driver();
	WebDriver driver = test.getInstance();
       rule.setDriver(driver);
	
	MovieUI ui = test.getGui(driver);

	assertTrue("ERROR: Privacy Link is not present",
			   ui.fluentWaitPresent(MovieUI.privacyLink));
	
	logger.info("INFO: Select Privacy link");
	WebElement link = ui.findElement(MovieUI.privacyLink);
	link.click();
	
	title = driver.getTitle();
	
	logger.info("INFO: Title of IBM Privacy page - " + title);
	
	//Validate that the title of page for IBM Privacy matches expected
	assertTrue("ERROR: Title of page - " + title + " does not match expected title of the IBM Privacy page - " + expectedTitle,
						title.contains(expectedTitle));		
}
 
Example 10
Source File: SeleniumBrowser.java    From OpenID-Attacker with GNU General Public License v2.0 5 votes vote down vote up
private static boolean hasQuit(WebDriver driver) {
        try {
            driver.getTitle();
            return false;
        } catch (Exception e) {
            return true;
        }
}
 
Example 11
Source File: WebDriverService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tries to focus the browser window thanks to the title given by the
 * webdriver in order to put it in foreground for Robot to work (Only works
 * on Windows so far, another way is to find for Xorg)
 *
 * @param session Webdriver session instance
 * @return True if the window is found, False otherwise
 */
public boolean focusBrowserWindow(Session session) {
    WebDriver driver = session.getDriver();
    String title = driver.getTitle();
    try {
        User32 user32 = User32.instance;

        // Arbitrary
        String[] browsers = new String[]{
            "",
            "Google Chrome",
            "Mozilla Firefox",
            "Opera",
            "Safari",
            "Internet Explorer",
            "Microsoft Edge",};

        for (String browser : browsers) {
            HWND window;
            if (browser.isEmpty()) {
                window = user32.FindWindow(null, title);
            } else {
                window = user32.FindWindow(null, title + " - " + browser);
            }
            if (user32.ShowWindow(window, User32.SW_SHOW)) {
                return user32.SetForegroundWindow(window);
            }
        }

    } catch (Exception e) {
        LOG.error(e, e);
    }

    return false;
}
 
Example 12
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String driverOperation(WebDriver wd, String operation, String operationValue) {
    String result = "";
    // ����ҳ��������
    switch (operation) {
        case "open":
            wd.get(operationValue);
            result = "Openҳ��...��" + operationValue + "��";
            LogUtil.APP.info("Openҳ��...��{}��",operationValue);
            break;
        case "addcookie":
            List<Cookie> cookies = buildCookie(operationValue);
            if (null != cookies && cookies.size() > 0) {
                for (Cookie cookie : cookies) {
                    wd.manage().addCookie(cookie);
                    LogUtil.APP.info("���Cookie:��{}���ɹ���",cookie);
                }
            }
            result = "���cookie...��" + operationValue + "��";
            break;
        case "exjs":
            JavascriptExecutor jse = (JavascriptExecutor) wd;
            Object obj = jse.executeScript(operationValue);
            if (null != obj) {
                String tmp = obj.toString();
                result = (100 < tmp.length()) ? tmp.substring(0, 100) + "..." : tmp;
                result = "��ȡ����ֵ�ǡ�" + result + "��";
                LogUtil.APP.info("ִ��JS...��{}�������صĽ��Ϊ:{}",operationValue,result);
            } else {
                result = "ִ��JS...��" + operationValue + "��";
                LogUtil.APP.info("{}��ִ��JS����null��û�з���",result);
            }
            break;
        case "gotodefaultcontent":
            wd.switchTo().defaultContent();
            result = "gotodefaultcontent�л���Ĭ��ҳ��λ��...";
            LogUtil.APP.info(result);
            break;
        case "gotoparentframe":
            wd.switchTo().parentFrame();
            result = "gotoparentframe�л�����һ��frameλ��...";
            LogUtil.APP.info(result);
            break;
        case "gettitle":
            result = "��ȡ����ֵ�ǡ�" + wd.getTitle() + "��";
            LogUtil.APP.info("��ȡҳ��Title...��{}��",wd.getTitle());
            break;
        case "getwindowhandle":
            result = getTargetWindowHandle(wd, operationValue);
            break;
        case "gotowindow":
            result = switchToTargetWindow(wd, operationValue);
            break;
        case "closewindow":
            wd.close();
            result = "�رյ�ǰ���������...";
            break;
        case "pagerefresh":
            wd.navigate().refresh();
            result = "ˢ�µ�ǰ���������...";
            break;
        case "pageforward":
            wd.navigate().forward();
            result = "ǰ����ǰ���������...";
            break;
        case "pageback":
            wd.navigate().back();
            result = "���˵�ǰ���������...";
            break;
        case "timeout":
            try {
                // ����ҳ��������ʱ��30��
                wd.manage().timeouts().pageLoadTimeout(Integer.parseInt(operationValue), TimeUnit.SECONDS);
                // ����Ԫ�س������ʱ��30��
                wd.manage().timeouts().implicitlyWait(Integer.parseInt(operationValue), TimeUnit.SECONDS);
                result = "��ǰ��������ȴ���" + operationValue + "����...";
                LogUtil.APP.info("��ǰ��������ȴ���{}����...",operationValue);
                break;
            } catch (NumberFormatException e) {
                LogUtil.APP.error("�ȴ�ʱ��ת�������쳣��",e);
                result = "���ȴ�ʱ��ת���������������";
                break;
            }
        default:
            break;
    }
    return result;
}
 
Example 13
Source File: BrowserTestCase.java    From caja with Apache License 2.0 4 votes vote down vote up
/**
 * Do what should be done with the browser.
 */
protected String driveBrowser(final WebDriver driver) {
  // long timeout: something we're doing is leading to huge unpredictable
  // slowdowns in random test startup; perhaps we're holding onto a lot of ram
  // and  we're losing on swapping/gc time.  unclear.
  countdown(10000, 200, new Countdown() {
    @Override public String toString() { return "startup"; }
    public int run() {
      List<WebElement> readyElements = driver.findElements(
          By.className("readytotest"));
      return readyElements.size() == 0 ? 1 : 0;
    }
  });

  // 4s because test-domado-dom-events has non-click tests that can block
  // for a nontrivial amount of time, so our clicks aren't necessarily
  // processed right away.
  countdown(4000, 200, new Countdown() {
    private List<WebElement> clickingList = null;
    @Override public String toString() {
      return "clicking done (Remaining elements = " +
          renderElements(clickingList) + ")";
    }
    public int run() {
      clickingList = driver.findElements(By.xpath(
          "//*[contains(@class,'clickme')]/*"));
      for (WebElement e : clickingList) {
        // TODO(felix8a): webdriver fails if e has been removed
        e.click();
      }
      return clickingList.size();
    }
  });

  // override point
  waitForCompletion(driver);

  // check the title of the document
  String title = driver.getTitle();
  assertTrue("The title shows " + title, title.contains("all tests passed"));
  return title;
}
 
Example 14
Source File: GetTitle.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
protected String handleSeleneseCommand(WebDriver driver, String ignored, String alsoIgnored) {
  return driver.getTitle();
}