Example usage for org.openqa.selenium WebElement getTagName

List of usage examples for org.openqa.selenium WebElement getTagName

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement getTagName.

Prototype

String getTagName();

Source Link

Document

Get the tag name of this element.

Usage

From source file:sf.wicklet.gwt.site.test.support.FirefoxTestBase.java

License:Apache License

protected void click(final List<WebElement> a) {
    if (debug().isDebug()) {
        System.out.println("### click(): " + a.size());
        for (final WebElement e : a) {
            System.out.println(e.getTagName() + ": " + e.getLocation() + ": " + getLink(e));
        }// w  ww.j a  v  a  2s .  c om
    }
    assertTrue(a.size() > 0);
    a.get(0).click();
}

From source file:sLinkValidator.RunnableLinkChecker.java

License:Apache License

public void run() {

    long numThreadId = Thread.currentThread().getId();
    String exp_msg = null;//w  ww.j av  a 2  s  .co  m
    String strPtnProtocol = "https{0,1}://";

    strFname_ok.set("results" + File.separator + "__tmp_" + Long.toString(numThreadId) + "_" + strThreadID
            + "__healthy_links.csv");
    strFname_error.set("results" + File.separator + "__tmp_" + Long.toString(numThreadId) + "_" + strThreadID
            + "__broken_links.csv");
    strFname_externalLinks.set("results" + File.separator + "__tmp_" + Long.toString(numThreadId) + "_"
            + strThreadID + "__external_links.csv");
    strFname_exceptions.set("results" + File.separator + "__tmp_" + Long.toString(numThreadId) + "_"
            + strThreadID + "__exceptions.txt");

    // shared variables from BrokenLinkChecker class.
    String strRootURL = LinkValidator.getRootURL();
    boolean boolOptAny = LinkValidator.getOptAny();
    boolean boolOptVerbose = LinkValidator.getOptVerboseFlg();
    boolean boolOptCapture = LinkValidator.getOptScreenCaptureFlg();
    boolean boolOptSkipElement = LinkValidator.getOptSkipElementFlg();
    boolean boolOptSitemapMode = LinkValidator.getSitemapModeFlg();

    ConcurrentHashMap<String, Integer> visitedLinkMap = LinkValidator.getVisitedLinkMap();
    //ConcurrentLinkedDeque<String> stack = LinkValidator.getStack();
    ConcurrentLinkedDeque<String> deque = LinkValidator.getDeque();
    ConcurrentLinkedDeque<FirefoxDriver> dqBrowserDrivers = LinkValidator.getDQBrowserDrivers();

    FirefoxDriver browserDriver = dqBrowserDrivers.pop();

    try {

        f_out_ok.set(new FileOutputStream(strFname_ok.get()));
        f_out_error.set(new FileOutputStream(strFname_error.get()));
        f_out_externalLinks.set(new FileOutputStream(strFname_externalLinks.get()));
        f_out_exceptions.set(new FileOutputStream(strFname_exceptions.get()));

        if (boolOptVerbose) {
            System.out.println("[Current Target] : " + this.strURL);
        }
        new PrintStream(f_out_ok.get()).println("[Current Target] : " + this.strURL);

        visitedLinkMap.putIfAbsent(this.strURL, 1);

        String url_get = "";

        if (this.uid != "" || this.password != "") {
            url_get = this.strURL.replaceFirst("(" + strPtnProtocol + ")",
                    "$1" + this.uid + ":" + this.password + "@"); // add id and pass to URL (e.g. https{0,1}:// -> https{0,1}://uid:password@ )
        } else {
            url_get = this.strURL;
        }

        browserDriver.get(url_get);

        if (boolOptCapture) {
            // take the screenshot of the browsing page.

            //
            // replace some characters in url to use it as the capture images filename(png).
            //
            //String url_httpTrimed_01 = this.strURL.replaceFirst("^https{0,1}://[^/]+/", "");
            String url_httpTrimed_01 = this.strURL.replaceFirst("^" + strPtnProtocol + "[^/]+/?", ""); //trim protocol and hostname from URL. (e.g. http(s)://hostname/path -> path)
            String url_httpTrimed_02 = url_httpTrimed_01.replaceAll("[/?\"<>|:*]", "_");

            Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
                    .takeScreenshot(browserDriver);
            File f_ScreenShot = new File("results" + File.separator + "screenshot" + File.separator
                    + URLDecoder.decode(url_httpTrimed_02, "UTF-8") + ".png");
            File parentDir = f_ScreenShot.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                if (!parentDir.mkdirs()) {
                    throw new IOException("error creating results/screenshot directory");
                }
            }
            if (!f_ScreenShot.exists()) {
                ImageIO.write(fpScreenshot.getImage(), "PNG", f_ScreenShot);
            }

        }

        if (!boolOptSkipElement) {

            ArrayList<WebElement> allLinks = findAllLinks(browserDriver, boolOptAny);

            if (boolOptVerbose) {
                System.out.println("Total number of elements found " + allLinks.size());
            }
            new PrintStream(f_out_ok.get()).println("Total number of elements found " + allLinks.size());
            URL objTgtURL = null;

            for (WebElement element : allLinks) {

                try {
                    String strTagName = element.getTagName();
                    String strTgtURL = null;
                    String linkType = "";
                    String linkText = "";
                    String altText = "";

                    if (strTagName.equalsIgnoreCase("a")) {
                        strTgtURL = element.getAttribute("href");
                        linkType = "<a>";
                        linkText = element.getText();
                    } else if (!boolOptSitemapMode && strTagName.equalsIgnoreCase("img")) {
                        strTgtURL = element.getAttribute("src");
                        linkType = "<img>";
                        altText = element.getAttribute("alt");
                    } else if (!boolOptSitemapMode && strTagName.equalsIgnoreCase("link")) {
                        strTgtURL = element.getAttribute("href");
                        linkType = "<link>";
                        linkText = element.getText();
                    }

                    ResponseDataObj respData;

                    if (strTgtURL != null) {
                        String msg = null;
                        //String noUidPwdURL = strTgtURL.replaceFirst( "(https{0,1}://)" + this.uid + ":" + this.password + "@", "$1" );
                        String noUidPwdURL = strTgtURL.replaceFirst(
                                "(" + strPtnProtocol + ")" + this.uid + ":" + this.password + "@", "$1"); // trim uid and password (e.g. https{0,1}://uid:password@ -> https{0,1}://)
                        String noUidPwdURL_decoded = java.net.URLDecoder.decode(noUidPwdURL,
                                StandardCharsets.UTF_8.name());

                        if (visitedLinkMap.containsKey(noUidPwdURL_decoded)) {

                            //msg = this.strURL + "\t" + linkType + "\t" + noUidPwdURL_decoded + "\t" + "(visited)";
                            msg = "\"" + handleDoubleQuoteForCSV(this.strURL) + "\"" + "," + linkType + ","
                                    + handleDoubleQuoteForCSV(noUidPwdURL_decoded) + "," + "(visited)" + ","
                                    + "," + ",";
                            new PrintStream(f_out_ok.get()).println(msg);

                        } else if (strTagName.equalsIgnoreCase("a")
                                && isExternalSite(strRootURL, noUidPwdURL_decoded)) {
                            // external link

                            // msg = this.strURL + "\t" + linkType + "\t" + noUidPwdURL_decoded + "\t" + "(external link)";
                            msg = "\"" + this.strURL + "\"" + "," + linkType + "," + "\""
                                    + handleDoubleQuoteForCSV(noUidPwdURL_decoded) + "\"" + ","
                                    + "(external link)" + "," + "," + ",";
                            new PrintStream(f_out_externalLinks.get()).println(msg);
                            Integer prevCount = (Integer) numExternalLinks.get();
                            numExternalLinks.set(new Integer(prevCount.intValue() + 1));
                        } else {

                            // (Note)
                            // at this moment, objTgtURL is always null because of finally() part.

                            Matcher mtch_no_http = ptn_no_http.matcher(strTgtURL);
                            if (mtch_no_http.find()) // if strTgtURL was relative.
                            {
                                objTgtURL = new URL(new URL(strRootURL), strTgtURL);
                            } else {
                                objTgtURL = new URL(strTgtURL);
                            }

                            respData = isLinkBroken(objTgtURL, uid, password);
                            visitedLinkMap.put(noUidPwdURL_decoded, 1);

                            if ((this.boolRunAsBFSSearch == true)
                                    && !(strTgtURL.contains("mailto:") || strTgtURL.contains("tel:"))
                                    && strTagName.equalsIgnoreCase("a") && !deque.contains(noUidPwdURL_decoded)
                                    && !(strTgtURL.lastIndexOf("#") > strTgtURL.lastIndexOf("/"))
                                    && !(strTgtURL.endsWith(".png") || strTgtURL.endsWith(".jpg")
                                            || strTgtURL.endsWith(".gif"))) { // Do not access to not-A-tag URL via Firefox driver.
                                //stack.push(noUidPwdURL);  // stack
                                deque.addLast(noUidPwdURL_decoded); // queue
                            }

                            /*
                            msg = this.strURL 
                                  + "\t" + linkType
                                  + "\t" + noUidPwdURL_decoded
                                  + "\t" + respData.getRespMsg() 
                                  + "\t" + respData.getRespCode()
                                  + "\t" + altText.replaceAll("\r", "").replaceAll("\n", "")
                                  + "\t" + linkText.replaceAll("\r", "").replaceAll("\n", "");
                            */
                            msg = "\"" + handleDoubleQuoteForCSV(this.strURL) + "\"" + "," + linkType + ","
                                    + "\"" + handleDoubleQuoteForCSV(noUidPwdURL_decoded) + "\"" + ","
                                    + respData.getRespMsg() + "," + respData.getRespCode() + "," + "\""
                                    + altText.replaceAll("\r", "").replaceAll("\n", "").replaceAll("\"", "\"\"")
                                    + "\"" + "," + "\"" + linkText.replaceAll("\r", "").replaceAll("\n", "")
                                            .replaceAll("\"", "\"\"")
                                    + "\"";

                            if (respData.getRespCode() >= 400) {
                                new PrintStream(f_out_error.get()).println(msg);
                                Integer prevCount = (Integer) numInvalidLink.get();
                                numInvalidLink.set(new Integer(prevCount.intValue() + 1));
                            } else {
                                new PrintStream(f_out_ok.get()).println(msg);
                                Integer prevCount = (Integer) numHealthyLink.get();
                                numHealthyLink.set(new Integer(prevCount.intValue() + 1));
                            }
                        }

                        if (boolOptVerbose) {
                            System.out.println(msg);
                        }

                    }

                } catch (UnsupportedEncodingException e) {
                    // not going to happen - value came from JDK's own StandardCharsets
                    // just for noUidPwdURL_decoded in case something wrong happens
                    exp_msg = this.strURL + "\t" + "At attribute : \"" + element.getAttribute("innerHTML")
                            + "\".\t" + "[UnsupportedEncodingException] Message  :  " + e.getMessage();
                    System.out.println(exp_msg);
                    new PrintStream(f_out_exceptions.get()).println(exp_msg);
                    Integer prevCount = (Integer) numExceptions.get();
                    numExceptions.set(new Integer(prevCount.intValue() + 1));

                } catch (Exception exp) {
                    exp_msg = this.strURL + "\t" + "At attribute : \"" + element.getAttribute("innerHTML")
                            + "\".\t" + "Message  :  " + exp.getMessage();
                    System.out.println(exp_msg);
                    new PrintStream(f_out_exceptions.get()).println(exp_msg);
                    Integer prevCount = (Integer) numExceptions.get();
                    numExceptions.set(new Integer(prevCount.intValue() + 1));
                } finally {
                    objTgtURL = null;
                }

            }
        }

    } catch (Exception exp) {
        exp_msg = "[In Main Loop] An Exception occured at page " + this.strURL + " .\tMessage  :  "
                + exp.getMessage();
        System.out.println(exp_msg);
        new PrintStream(f_out_exceptions.get()).println(exp_msg);
        Integer prevCount = (Integer) numExceptions.get();
        numExceptions.set(new Integer(prevCount.intValue() + 1));
    } finally {

        // push back browserdriver to drivers-dequeue to reuse
        dqBrowserDrivers.addLast(browserDriver);

        // add obtained numbers to values in main class.
        LinkValidator.addAndGetNumHealthyLink(numHealthyLink.get());
        LinkValidator.addAndGetNumInvalidLink(numInvalidLink.get());
        LinkValidator.addAndGetNumExternalLinks(numExternalLinks.get());
        LinkValidator.addAndGetNumExceptions(numExceptions.get());

        try {
            f_out_ok.get().close();
            f_out_error.get().close();
            f_out_externalLinks.get().close();
            f_out_exceptions.get().close();
        } catch (IOException exp) {
            exp.printStackTrace();
            exp_msg = "[finally part in Main run()] An Exception occured at page " + this.strURL
                    + " .\tMessage  :  " + exp.getMessage();
            System.out.println(exp_msg);
            new PrintStream(f_out_exceptions.get()).println(exp_msg);
            Integer prevCount = (Integer) numExceptions.get();
            numExceptions.set(new Integer(prevCount.intValue() + 1));
            LinkValidator.addAndGetNumExceptions(numExceptions.get());
        }

        appendAndDeleteTmpFile(LinkValidator.getFStreamOutOk(), strFname_ok.get());
        appendAndDeleteTmpFile(LinkValidator.getFStreamOutError(), strFname_error.get());
        appendAndDeleteTmpFile(LinkValidator.getFStreamOutExternalSites(), strFname_externalLinks.get());
        appendAndDeleteTmpFile(LinkValidator.getFStreamOutExceptions(), strFname_exceptions.get());

    }

}

From source file:swift.selenium.CommonExpectedConditions.java

License:Open Source License

/**
 * An expectation for checking if the given text is present in the specified
 * element./*from w  ww.  j  a v a2s.  c o  m*/
 *
 * @author Michal Nowierski
 */
public static ExpectedCondition<Boolean> valueToBePresentInElementsAttribute(final WebElement element,
        final String attribute, final String value) {

    return new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver from) {
            try {
                String elementsAttributeValue = element.getAttribute(attribute);
                return elementsAttributeValue.contains(value);
            } catch (StaleElementReferenceException e) {
                return null;
            }
        }

        @Override
        public String toString() {
            return String.format("value ('%s') to be present in element found by %s", value,
                    element.getTagName());
        }
    };
}

From source file:swift.selenium.CommonExpectedConditions.java

License:Open Source License

/**
 * An Expectation for checking an element is visible and enabled such that you
 * can click it./*from  www.j  a  v  a  2 s. c  o m*/
 * 
 * @param GivenElement element to be checked
 * @author Michal Nowierski
 */
public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement GivenElement) {
    return new ExpectedCondition<WebElement>() {

        public ExpectedCondition<WebElement> visibilityOfElement = ExpectedConditions
                .visibilityOf(GivenElement);

        public WebElement apply(WebDriver driver) {
            WebElement element = visibilityOfElement.apply(driver);
            try {
                if (element != null && element.isEnabled()) {
                    return element;
                } else {
                    return null;
                }
            } catch (StaleElementReferenceException e) {
                return null;
            }
        }

        @Override
        public String toString() {
            return "element to be clickable: " + GivenElement.getTagName();
        }
    };
}

From source file:swift.selenium.CommonExpectedConditions.java

License:Open Source License

/**
 * An Expectation for checking an element is visible and not enabled such that you
 * can not click it.//from   w  w  w  . j  a  v a 2 s .c o m
 * 
 * @param GivenElement element to be checked
 * @author Michal Nowierski
 */
public static ExpectedCondition<WebElement> elementNotToBeClickable(final WebElement GivenElement) {
    return new ExpectedCondition<WebElement>() {

        public ExpectedCondition<WebElement> visibilityOfElement = ExpectedConditions
                .visibilityOf(GivenElement);

        public WebElement apply(WebDriver driver) {
            WebElement element = visibilityOfElement.apply(driver);
            try {
                if (element != null && !element.isEnabled()) {
                    return element;
                } else {
                    return null;
                }
            } catch (StaleElementReferenceException e) {
                return null;
            }
        }

        @Override
        public String toString() {
            return "element to be clickable: " + GivenElement.getTagName();
        }
    };
}

From source file:swift.selenium.CommonExpectedConditions.java

License:Open Source License

/**
 * An expectation for checking if the given text is present in the specified
 * element./*from   w w w . jav  a 2s  .  co m*/
 */
public static ExpectedCondition<Boolean> textToBePresentInElement(final WebElement GivenElement,
        final String text) {

    return new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver from) {
            try {
                String elementText = GivenElement.getText();
                return elementText.contains(text);
            } catch (StaleElementReferenceException e) {
                return null;
            }
        }

        @Override
        public String toString() {
            return String.format("text ('%s') to be present in element %s", text, GivenElement.getTagName());
        }
    };
}

From source file:swift.selenium.WebHelper.java

License:Open Source License

public static List<Object> getPropertiesOfWebElement(WebElement webElement, String imageType) {
    List<WebElement> elements = webElement.findElements(By.tagName(imageType));
    WebElement element = elements.get(0);
    List<Object> elementProperties = new ArrayList<Object>();
    String elementType = element.getAttribute("type");
    String elementTagName = element.getTagName();
    //String elementClassName = element.getClass().toString();
    String controlType = "";
    String id = "";
    String name = "";
    if (elementType.equals("text") && elementTagName.equals("input")) {
        id = element.getAttribute("id");
        name = element.getAttribute("name");
        controlType = "WebEdit";
    } else if (elementType.contains("checkbox") && elementTagName.equals("input")) {
        id = element.getAttribute("id");
        name = element.getAttribute("name");
        controlType = "CheckBox";
    } else if (elementType.contains("listbox") && elementTagName.equals("select")) {
        id = element.getAttribute("id");
        name = element.getAttribute("name");
        controlType = "WebList";
    } else if (elementType.contains("radio") && elementTagName.equals("input")) {
        id = element.getAttribute("id");
        name = element.getAttribute("name");
        controlType = "Radio";
    } else if (elementType.contains("") && elementTagName.equals("a")) {
        id = element.getAttribute("id");
        name = element.getAttribute("name");
        controlType = "WebLink";
    }//from  w ww.  j  a  v  a 2s  . c  om
    elementProperties.add(id);
    elementProperties.add(name);
    elementProperties.add(controlType);
    elementProperties.add((Object) element);
    return elementProperties;
}