Example usage for org.jsoup.nodes Element getElementsByClass

List of usage examples for org.jsoup.nodes Element getElementsByClass

Introduction

In this page you can find the example usage for org.jsoup.nodes Element getElementsByClass.

Prototype

public Elements getElementsByClass(String className) 

Source Link

Document

Find elements that have this class, including or under this element.

Usage

From source file:com.kantenkugel.discordbot.jdocparser.JDocParser.java

private static List<DocBlock> getDocBlock(String jdocBase, Element elem, ClassDocumentation reference) {
    if (elem != null) {
        String baseLink = JDocUtil.getLink(jdocBase, reference);
        List<DocBlock> blocks = new ArrayList<>(10);
        String hashLink = null;//from   w w w . j a v  a  2  s.c  o m
        for (elem = elem.nextElementSibling(); elem != null; elem = elem.nextElementSibling()) {
            if (elem.tagName().equals("a")) {
                hashLink = '#' + elem.attr("name");
            } else if (elem.tagName().equals("ul")) {
                Element tmp = elem.getElementsByTag("h4").first();
                String title = JDocUtil.fixSpaces(tmp.text().trim());
                String description = "", signature = "";
                OrderedMap<String, List<String>> fields = new ListOrderedMap<>();
                for (; tmp != null; tmp = tmp.nextElementSibling()) {
                    if (tmp.tagName().equals("pre")) {
                        //contains full signature
                        signature = JDocUtil.fixSpaces(tmp.text().trim());
                    } else if (tmp.tagName().equals("div") && tmp.className().equals("block")) {
                        //main block of content (description or deprecation)
                        Element deprecationElem = tmp.getElementsByClass("deprecationComment").first();
                        if (deprecationElem != null) {
                            //deprecation block
                            fields.put("Deprecated:", Collections
                                    .singletonList(JDocUtil.formatText(deprecationElem.html(), baseLink)));
                        } else {
                            //description block
                            description = JDocUtil.formatText(tmp.html(), baseLink);
                        }
                    } else if (tmp.tagName().equals("dl")) {
                        //a field
                        String fieldName = null;
                        List<String> fieldValues = new ArrayList<>();
                        for (Element element : tmp.children()) {
                            if (element.tagName().equals("dt")) {
                                if (fieldName != null) {
                                    fields.put(fieldName, fieldValues);
                                    fieldValues = new ArrayList<>();
                                }
                                fieldName = JDocUtil.fixSpaces(element.text().trim());
                            } else if (element.tagName().equals("dd")) {
                                fieldValues.add(JDocUtil.formatText(element.html(), baseLink));
                            }
                        }
                        if (fieldName != null) {
                            fields.put(fieldName, fieldValues);
                        }
                    }
                }
                blocks.add(new DocBlock(title, hashLink, signature, description, fields));
            }
        }
        return blocks;
    }
    return null;
}

From source file:Leitura.Ecobertura.java

public ArrayList<Integer> qtdeLinhasCod() {
    char[] aux;/*from  w w w  . jav  a  2s.  co m*/
    StringBuffer sbLinha = new StringBuffer();
    Elements elements = document.getElementsByTag("tr");
    for (Element children : elements) {
        if (StringUtils.isNotBlank(children.getElementsByClass("numLineCover").text())) {
            aux = children.getElementsByClass("numLineCover").text().toCharArray();
            for (int i = 0; i < aux.length; i++) {
                //System.out.println("["+aux[i]+"]");
                if (aux[i] >= 48 && aux[i] <= 57) {
                    sbLinha.append(aux[i]); // exclui espaos na string
                }
            }
            if (StringUtils.isNotBlank(sbLinha.toString())) {
                linhasCod.add(Integer.parseInt(sbLinha.toString()));
                sbLinha.delete(0, sbLinha.length());
            }
        }
    }
    return linhasCod;
}

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private static List<ConfluencePage> handlePagination() {
    final List<ConfluencePage> confluencePages = new ArrayList<>();
    final SwaggerConfluenceConfig swaggerConfluenceConfig = SWAGGER_CONFLUENCE_CONFIG.get();

    final PaginationMode paginationMode = swaggerConfluenceConfig.getPaginationMode();

    final Document originalDocument = SWAGGER_DOCUMENT.get();
    final Document transformedDocument = originalDocument.clone();

    final Elements categoryElements = transformedDocument.select(".sect1");

    // Remove ToC form the transformed document
    final Elements toc = transformedDocument.select(".toc");
    toc.html("");
    toc.unwrap();/*from   www  . ja va 2 s.c  om*/

    // For Single Page Mode, the incoming XHTML can be used directly.
    if (paginationMode == SINGLE_PAGE) {
        final ConfluencePage confluencePage = ConfluencePageBuilder.aConfluencePage()
                .withPageType(PageType.ROOT).withOriginalTitle(swaggerConfluenceConfig.getTitle())
                .withConfluenceTitle(buildConfluenceTitle(swaggerConfluenceConfig.getTitle(), null, null))
                .build();

        if (swaggerConfluenceConfig.isIncludeTableOfContentsOnSinglePage()) {
            confluencePage.setXhtml(originalDocument.html());
        } else {
            confluencePage.setXhtml(transformedDocument.html());
        }

        confluencePages.add(confluencePage);

        return confluencePages;
    }

    // Before beginning further processing, we need to know if we're in individual
    // page mode or not, as that will effect how we split the DOM. If we're in this
    // mode then the category pages will contain inner table of contents.
    final boolean individualPages = (paginationMode == INDIVIDUAL_PAGES);

    // From here on, if we're still proceeding then we know the meat of the document
    // will go in sub-pages. So for the master page, we will use the table of contents
    final Elements tocElements = originalDocument.select(".toc");

    final List<String> innerTocXHtmlList = new ArrayList<>();
    final Elements innerTocElements = originalDocument.select(".sectlevel2");

    for (final Element innerTocElement : innerTocElements) {
        // If we're in individual page mode, then we collect the inner ToCs
        if (individualPages) {
            final StringBuilder tocHtml = new StringBuilder();
            tocHtml.append("<div id=\"toc\" class=\"toc\">");
            tocHtml.append("<h4 id=\"toctitle\">Table of Contents</h4>");
            tocHtml.append("<div><ul class=\"sectlevel1\">");
            tocHtml.append(innerTocElement.html());
            tocHtml.append("</ul></div></div>");
            innerTocXHtmlList.add(tocHtml.toString());
        }
        // If we're in category page mode, then we strip out the inner table of contents.
        else {
            innerTocElement.html("");
            innerTocElement.unwrap();
        }
    }

    // Build the Root Page w/ the Appropriate Level of Table of Contents
    final ConfluencePage rootConfluencePage = ConfluencePageBuilder.aConfluencePage()
            .withPageType(PageType.ROOT).withOriginalTitle(swaggerConfluenceConfig.getTitle())
            .withConfluenceTitle(buildConfluenceTitle(swaggerConfluenceConfig.getTitle(), null, null))
            .withXhtml(tocElements.html()).build();
    confluencePages.add(rootConfluencePage);

    int category = 1;

    // Now we process the category pages
    for (final Element categoryElement : categoryElements) {
        // Fetch the title from the first child, which is the header element
        final String categoryTitle = categoryElement.children().first().text();

        // If we're in individual mode then we need these to be sub table of contents
        if (individualPages) {

            final ConfluencePage categoryConfluencePage = ConfluencePageBuilder.aConfluencePage()
                    .withPageType(PageType.CATEGORY).withOriginalTitle(categoryTitle)
                    .withConfluenceTitle(buildConfluenceTitle(categoryTitle, category, null))
                    .withXhtml(innerTocXHtmlList.get(category - 1)).build();
            confluencePages.add(categoryConfluencePage);

            final Elements individualElements = categoryElement.getElementsByClass("sect2");

            int individual = 1;

            for (final Element individualElement : individualElements) {
                final String individualTitle = individualElement.children().first().text();
                final ConfluencePage individualConfluencePage = ConfluencePageBuilder.aConfluencePage()
                        .withPageType(INDIVIDUAL).withOriginalTitle(individualTitle)
                        .withConfluenceTitle(buildConfluenceTitle(individualTitle, category, individual))
                        .withXhtml(individualElement.html()).build();
                confluencePages.add(individualConfluencePage);

                individual++;
            }

            category++;
            continue;
        }

        // If we're in category mode, we use the remaining page data
        final ConfluencePage categoryConfluencePage = ConfluencePageBuilder.aConfluencePage()
                .withPageType(PageType.CATEGORY).withOriginalTitle(categoryTitle)
                .withConfluenceTitle(buildConfluenceTitle(categoryTitle, category, null))
                .withXhtml(categoryElement.html()).build();
        confluencePages.add(categoryConfluencePage);

        category++;
    }

    return confluencePages;
}

From source file:Leitura.Ecobertura.java

public void escreveTxt() throws IOException { //mtodo para pegar os nomes dos mtodos declarados
    String auxLinha = null;/*from  w  w w.ja v  a  2 s  . co  m*/
    char aux[] = null;
    StringBuffer sbClasse = new StringBuffer();
    StringBuffer sbLinha = new StringBuffer();
    StringBuffer sbMetodo = new StringBuffer();
    String metodoTemp;
    boolean controleClasse = false;

    // Pega somente os elementos com tag "tr"
    Elements elements = document.getElementsByTag("tr");
    for (Element children : elements) {
        if (StringUtils.isBlank(children.text())) {
            continue;
        }
        children.getElementsByClass("comment").remove();
        // System.out.println(children.text());
        //----------------- Dispensa Comentrios -----------------
        //auxLinha = children.getElementsByTag("span").eq(0).text();
        /*if (auxLinha.contains("/*")) {
         comentario = true;
         } else if(auxLinha.contains("//")){
         comentario = true;
         controle = true;            // controla comentrio com //
         }
                
         if (auxLinha.contains("*//*")) {
                                   comentario = false;
                                   }else if(auxLinha.contains("\n") && controle == true){
                                   comentario = false;
                                   controle = false;
                                   }*/

        //------------------ Fim dispensa comentrios --------------

        // if (comentario == false) {
        //--------------------- verifica as linhas do cdigo -------------------
        if (StringUtils.isNotBlank(children.getElementsByClass("numLine").text())) {
            aux = children.getElementsByClass("numLine").text().toCharArray();

            for (int i = 0; i < aux.length; i++) {
                //System.out.println("["+aux[i]+"]");
                if (aux[i] >= 48 && aux[i] <= 57) { // pega o nmero da linha
                    sbLinha.append(aux[i]);
                }
            }
            auxLinha = sbLinha.toString();
            if (StringUtils.isNotBlank(auxLinha)) { // transforma a linha para inteiro
                qtdeLinhas = Integer.parseInt(auxLinha);
            }

            sbLinha.delete(0, sbLinha.length());
        }

        // ------------------- Fim linhas  ---------------------------------
        Elements pre = children.getElementsByTag("pre");
        for (Element element : pre) {
            String tagMetodo = element.getElementsByTag("span").eq(0).text();

            //------------------------- Verifica classe -------------------------
            if (element.getElementsByTag("span").text().contains("class")) {
                element.select("span.keyword").remove();
                if (controleClasse == false) {
                    classe = element.text().trim();
                    aux = classe.toCharArray();

                    for (int j = 0; j < aux.length; j++) {
                        if ((65 <= aux[j]) && (aux[j] <= 90) || (aux[j] >= 97) && (aux[j] <= 122)
                                || (aux[j] == 95)) {
                            sbClasse.append(aux[j]);
                            //System.out.println(j + ", " + sbClasse);
                            if (j < aux.length - 1) {
                                // System.out.println("size: "+aux.length+" j: "+j);
                                if ((aux[j + 1] == ' ') || (aux[j + 1] == '{') || (aux[j + 1] == '<')) {
                                    // System.out.println("entrei");
                                    if ((j + 1) < aux.length - 1) {
                                        for (int k = j++; k < aux.length; k++) {
                                            aux[k] = ' ';
                                        }
                                    }
                                }
                            }
                        }
                    }

                    excluiLinhas.add(qtdeLinhas);
                    classe = sbClasse.toString().replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", "");

                    controleClasse = true;
                }
                //  System.out.println("Classe: " + classe);
            } //------------------------------- Fim verifica classe------------------------------
              //------------------------------ Verifica mtodo ----------------------------------
              //else if (tagMetodo.equals("privtate") || tagMetodo.equals("public") || tagMetodo.equals("protected")) {
            else if (element.getElementsByTag("span").text().contains("privtate")
                    || element.getElementsByTag("span").text().contains("public")
                    || element.getElementsByTag("span").text().contains("protected")
                    || element.getElementsByTag("span").text().contains("static")
                    || element.getElementsByTag("span").text().contains("final")
                    || element.getElementsByTag("span").text().contains("native")
                    || element.getElementsByTag("span").text().contains("synchronized")
                    || element.getElementsByTag("span").text().contains("abstract")
                    || element.getElementsByTag("span").text().contains("threadsafe")
                    || element.getElementsByTag("span").text().contains("transient")) {
                element.select("span.keyword").remove();
                if (!element.text().contains("=") && !element.text().contains(".")
                        && !element.text().contains("@")) {
                    String[] s = element.text().split(" ");
                    for (int i = 0; i < s.length; i++) {
                        if (s[i].contains("(")) {
                            aux = s[i].toCharArray();
                            for (int j = 0; j < aux.length; j++) {
                                if (aux[j] == '(') {
                                    for (int k = j; k < aux.length; k++) {
                                        aux[k] = ' ';
                                    }
                                    break;
                                }
                                sbMetodo.append(aux[j]);
                            }
                            metodoTemp = sbMetodo.toString();
                            if (!metodoTemp.isEmpty()) {
                                metodo = metodoTemp.replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n",
                                        "");
                                sbMetodo.delete(0, aux.length);
                                informacoes = new Informacoes(classe, metodo, Integer.parseInt(auxLinha));
                                inf.add(informacoes);
                            }
                        }
                    }
                }
            }

            // --------------------------- Fim Verifica Mtodo ------------------------------------
        }

        // }
    }
    /* for(int i=0; i<inf.size(); i++){
     System.out.println("Classe:"+inf.get(i).getClasse()+" Metodo:"+inf.get(i).getMetodo()+" Linha: "+inf.get(i).getLinha());
     }
     //
            
     /* for(Map.Entry<String,Informacoes> entry : inf.entrySet()) {
      String key = entry.getKey();
      int value = entry.getValue().getLinha();
      String metodov = entry.getValue().getMetodo();
      String classev = entry.getValue().getClasse();
            
      System.out.println(key + " => " + classev+ " => " +metodov+ " => " +value);
      }*/
}

From source file:ie.nuim.cs.dri.metadata.WebSearch.java

/**
 *
 * @param title the title of the ROS//w  w  w .  j  a  v a 2 s . c om
 */
public void searchGoogle(String title) {
    String searchTitle = buildGoogleSearchTitle(title);
    boolean found = false;
    String publication = "";
    String publicationType = "";
    int citationCount = -1;
    String url = "http://scholar.google.com/scholar?" + searchTitle;
    Document doc = Jsoup.parse(getGS());
    Elements aElement = doc.getElementsByTag("h3");
    System.out.println("=====searching google=======");
    for (Element e : aElement) {
        Elements bElement = e.getElementsByTag("a");
        for (Element f : bElement) {
            System.out.println(f.text() + "\t" + title);

            if (title.equalsIgnoreCase(f.text())) {
                found = true;
                break;
            }
        }
        // System.out.println(e);

    }
    if (found == true) {
        Elements pElement = doc.getElementsByTag("div");
        for (Element p : pElement) {
            Elements pubElement = p.getElementsByClass("gs_a");
            for (Element pub : pubElement) {
                System.out.println(pub);
            }

        }
        for (Element p : pElement) {
            Elements pubElement = p.getElementsByClass("gs_fl");
            for (Element pub : pubElement) {
                System.out.println(pub);
            }

        }

    }
}

From source file:com.ferasinfotech.gwreader.ScreenSlidePageFragment.java

/**
 * Alternate Factory method for this fragment class. Constructs a new fragment for the given page number,
 * and HTML story element.//from w ww . j a v a 2s. c o  m
 */
public static ScreenSlidePageFragment create(int pageNumber, int numPages, org.jsoup.nodes.Element story) {
    int story_id = -1;
    String name = "";
    String summary = "";
    String headline = "";
    String cover_photo_url = "";
    String story_string = "";
    long createdAt;

    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
    Bundle args = new Bundle();
    if (pageNumber == 0) {
        story_id = 0;
        name = "Grasswire Help";
        headline = "Usage Instructions";
        cover_photo_url = "android.resource://com.ferasinfotech.gwreader/" + R.drawable.gw_logo;
        summary = "Swipe right and left to read each story.\n\n"
                + "Scroll down to read facts and associated news items (tweets and links) for each story.\n\n"
                + "Tap on a news items within a story and you'll be able to follow web links, view tweets via the Twitter app, or watch videos.\n\n"
                + "A long press on a story's cover photo will launch the device browser to view or edit the story on the Grasswire mobile site.\n\n"
                + "A long press on the image above will launch the Grasswire main page.\n\n" + "App Version: "
                + BuildConfig.VERSION_NAME + "\n\n";
    } else {

        // doing a story page, Element 'story' is the story data

        Elements e_list;
        org.jsoup.nodes.Element tag;

        story_id = Integer.valueOf(story.attr("data-story-id"));
        e_list = story.getElementsByClass("feature__tag");
        tag = e_list.get(0);
        name = tag.text() + " (" + pageNumber + "/" + numPages + ")";
        e_list = story.getElementsByClass("story__summary");
        tag = e_list.get(0);
        summary = tag.html().replace("<br />", "\r");
        e_list = story.getElementsByClass("feature__text");
        tag = e_list.get(0);
        headline = tag.text();
        e_list = story.getElementsByClass("feature__image");
        tag = e_list.get(0);
        cover_photo_url = tag.attr("src");
        story_string = story.toString();

    }

    args.putInt(ARG_PAGE, pageNumber);
    args.putInt(ARG_STORY_ID, story_id);
    args.putString(ARG_TITLE, name);
    args.putString(ARG_SUMMARY, summary);
    args.putString(ARG_HEADLINE, headline);
    args.putString(ARG_COVER_PHOTO, cover_photo_url);
    args.putString(ARG_STORY_STRING, "<html><head></head><body>" + story_string + "</body></html>");
    fragment.setArguments(args);
    return fragment;
}

From source file:net.kevxu.purdueassist.course.ScheduleDetail.java

private ScheduleDetailEntry parseDocument(Document document)
        throws HtmlParseException, CourseNotFoundException, ResultNotMatchException {
    ScheduleDetailEntry entry = new ScheduleDetailEntry(term, crn);
    Elements tableElements = document.getElementsByAttributeValue("summary",
            "This table is used to present the detailed class information.");

    if (!tableElements.isEmpty()) {
        for (Element tableElement : tableElements) {
            // get basic info for selected course
            Element tableBasicInfoElement = tableElement.getElementsByClass("ddlabel").first();
            if (tableBasicInfoElement != null) {
                setBasicInfo(entry, tableBasicInfoElement.text());
            } else {
                throw new HtmlParseException("Basic info element empty.");
            }/*from  w w  w. j  av  a 2s .c  o  m*/

            // get detailed course info
            Element tableDetailedInfoElement = tableElement.getElementsByClass("dddefault").first();

            if (tableDetailedInfoElement != null) {
                // process seat info
                Elements tableSeatDetailElements = tableDetailedInfoElement.getElementsByAttributeValue(
                        "summary", "This layout table is used to present the seating numbers.");
                if (tableSeatDetailElements.size() == 1) {
                    Element tableSeatDetailElement = tableSeatDetailElements.first();
                    Elements tableSeatDetailEntryElements = tableSeatDetailElement.getElementsByTag("tbody")
                            .first().children();
                    if (tableSeatDetailEntryElements.size() == 3 || tableSeatDetailEntryElements.size() == 4) {
                        setSeats(entry, tableSeatDetailEntryElements.get(1).text());
                        setWaitlistSeats(entry, tableSeatDetailEntryElements.get(2).text());
                        if (tableSeatDetailEntryElements.size() == 4) {
                            setCrosslistSeats(entry, tableSeatDetailEntryElements.get(3).text());
                        }
                    } else {
                        throw new HtmlParseException("Seat detail entry elements size not 3. We have "
                                + tableSeatDetailEntryElements.size() + ".");
                    }
                } else {
                    throw new HtmlParseException(
                            "Seat detail elements size not 1. We have " + tableSeatDetailElements.size() + ".");
                }
                // remove the seat info from detailed info
                tableSeatDetailElements.remove();

                // remaining information
                setRemainingInfo(entry, tableDetailedInfoElement.html());

            } else {
                throw new HtmlParseException("Detailed info element empty.");
            }

        }
    } else {
        // test empty
        Elements informationElements = document.getElementsByAttributeValue("summary",
                "This layout table holds message information");
        if (!informationElements.isEmpty()
                && informationElements.text().contains("No detailed class information found")) {
            throw new CourseNotFoundException(informationElements.text());
        } else {
            throw new HtmlParseException(
                    "Course table not found, but page does not contain message stating no course found.");
        }
    }

    return entry;
}

From source file:jp.mau.twappremover.MainActivity.java

private void getApps() {
    _apps.clear();//  w w w. j a v a 2s .c o  m

    HttpGet request = new HttpGet(APP_PAGE);
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Cookie", "_twitter_sess=" + _session_id + "; auth_token=" + _cookie_auth);

    try {
        String result = _client.execute(request, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    return EntityUtils.toString(response.getEntity(), "UTF-8");
                case HttpStatus.SC_NOT_FOUND:
                    throw new RuntimeException("not found");
                default:
                    throw new RuntimeException("error");
                }
            }
        });

        Document doc = null;
        doc = Jsoup.parse(result);

        // parse top page and get authenticity token
        Elements forms = doc.getElementsByTag("form");
        for (Element e : forms) {
            Elements auths = e.getElementsByAttributeValue("name", "authenticity_token");
            if (auths.size() > 0) {
                _auth_token = auths.get(0).attr("value");
                break;
            }
        }

        Elements apps = doc.getElementsByClass("app");
        for (Element e : apps) {
            LinkedApp app = new LinkedApp();
            if (e.getElementsByTag("strong").size() > 0)
                app.name = e.getElementsByTag("strong").get(0).text();
            if (e.getElementsByClass("creator").size() > 0)
                app.creator = e.getElementsByClass("creator").get(0).text();
            if (e.getElementsByClass("description").size() > 0)
                app.desc = e.getElementsByClass("description").get(0).text();
            if (e.getElementsByClass("app-img").size() > 0)
                app.imgUrl = e.getElementsByClass("app-img").get(0).attr("src");
            if (e.getElementsByClass("revoke").size() > 0) {
                String tmp = e.getElementsByClass("revoke").get(0).attr("id");
                app.revokeId = tmp.replaceAll(KEY_HEADER_REVOKE, "");
            } else {
                // revoke id ????(facebook????????)
                continue;
            }
            _apps.add(app);
        }
        _handler.post(new Runnable() {
            @Override
            public void run() {
                _appadapter.notifyDataSetChanged();
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.screenslicer.core.util.BrowserUtil.java

private static WebElement toElement(Browser browser, HtmlNode htmlNode, Element body, boolean recurse)
        throws ActionFailed {
    if (body == null) {
        body = BrowserUtil.openElement(browser, true, null, null, null, null);
    }// w w  w.  j a va  2  s.  co m
    if (!CommonUtil.isEmpty(htmlNode.id)) {
        Elements elements = body.getElementsByAttributeValue("id", htmlNode.id);
        if (elements.size() == 1) {
            WebElement element = toElement(browser, elements.get(0), htmlNode, recurse);
            if (element != null) {
                return element;
            }
        }
    }
    List<Elements> selected = new ArrayList<Elements>();
    if (!CommonUtil.isEmpty(htmlNode.tagName)) {
        selected.add(body.getElementsByTag(htmlNode.tagName));
    } else if (!CommonUtil.isEmpty(htmlNode.href)) {
        selected.add(body.getElementsByTag("a"));
    }
    if (!CommonUtil.isEmpty(htmlNode.id)) {
        selected.add(body.getElementsByAttributeValue("id", htmlNode.id));
    }
    if (!CommonUtil.isEmpty(htmlNode.name)) {
        selected.add(body.getElementsByAttributeValue("name", htmlNode.name));
    }
    if (!CommonUtil.isEmpty(htmlNode.type)) {
        selected.add(body.getElementsByAttributeValue("type", htmlNode.type));
    }
    if (!CommonUtil.isEmpty(htmlNode.value)) {
        selected.add(body.getElementsByAttributeValue("value", htmlNode.value));
    }
    if (!CommonUtil.isEmpty(htmlNode.title)) {
        selected.add(body.getElementsByAttributeValue("title", htmlNode.title));
    }
    if (!CommonUtil.isEmpty(htmlNode.role)) {
        selected.add(body.getElementsByAttributeValue("role", htmlNode.role));
    }
    if (!CommonUtil.isEmpty(htmlNode.alt)) {
        selected.add(body.getElementsByAttributeValue("alt", htmlNode.alt));
    }
    if (htmlNode.classes != null && htmlNode.classes.length > 0) {
        Map<Element, Integer> found = new HashMap<Element, Integer>();
        for (int i = 0; i < htmlNode.classes.length; i++) {
            Elements elements = body.getElementsByClass(htmlNode.classes[i]);
            for (Element element : elements) {
                if (!found.containsKey(element)) {
                    found.put(element, 0);
                }
                found.put(element, found.get(element) + 1);
            }
        }
        Elements elements = new Elements();
        for (int i = htmlNode.classes.length; i > 0; i--) {
            for (Map.Entry<Element, Integer> entry : found.entrySet()) {
                if (entry.getValue() == i) {
                    elements.add(entry.getKey());
                }
            }
            if (!elements.isEmpty()) {
                break;
            }
        }
        selected.add(elements);
    }
    if (!CommonUtil.isEmpty(htmlNode.href)) {
        Elements hrefs = body.getElementsByAttribute("href");
        Elements toAdd = new Elements();
        String currentUrl = browser.getCurrentUrl();
        String hrefGiven = htmlNode.href;
        for (Element href : hrefs) {
            String hrefFound = href.attr("href");
            if (hrefGiven.equalsIgnoreCase(hrefFound)) {
                toAdd.add(href);
                toAdd.add(href);
                toAdd.add(href);
            } else if (htmlNode.fuzzy && hrefFound != null && hrefFound.endsWith(hrefGiven)) {
                toAdd.add(href);
                toAdd.add(href);
            } else if (htmlNode.fuzzy && hrefFound != null && hrefFound.contains(hrefGiven)) {
                toAdd.add(href);
            } else {
                String uriGiven = UrlUtil.toCanonicalUri(currentUrl, hrefGiven);
                String uriFound = UrlUtil.toCanonicalUri(currentUrl, hrefFound);
                if (uriGiven.equalsIgnoreCase(uriFound)) {
                    toAdd.add(href);
                }
            }
        }
        selected.add(toAdd);
    }
    if (!CommonUtil.isEmpty(htmlNode.innerText)) {
        selected.add(body.getElementsMatchingText(Pattern.quote(htmlNode.innerText)));
        selected.add(body.getElementsMatchingText("^\\s*" + Pattern.quote(htmlNode.innerText) + "\\s*$"));
    }
    if (htmlNode.multiple != null) {
        selected.add(body.getElementsByAttribute("multiple"));
    }
    Map<Element, Integer> votes = new HashMap<Element, Integer>();
    for (Elements elements : selected) {
        for (Element element : elements) {
            if (!votes.containsKey(element)) {
                votes.put(element, 0);
            }
            votes.put(element, votes.get(element) + 2);
            if (!NodeUtil.isHidden(element)) {
                votes.put(element, votes.get(element) + 1);
            }
        }
    }
    int maxVote = 0;
    Element maxElement = null;
    for (Map.Entry<Element, Integer> entry : votes.entrySet()) {
        if (entry.getValue() > maxVote) {
            maxVote = entry.getValue();
            maxElement = entry.getKey();
        }
    }
    return toElement(browser, maxElement, htmlNode, recurse);
}

From source file:com.screenslicer.core.util.Util.java

public static WebElement toElement(RemoteWebDriver driver, HtmlNode htmlNode, Element body)
        throws ActionFailed {
    if (body == null) {
        body = Util.openElement(driver, null, null, null);
    }/* w ww . ja  v a 2  s .  c o m*/
    if (!CommonUtil.isEmpty(htmlNode.id)) {
        WebElement element = toElement(driver, body.getElementById(htmlNode.id));
        if (element != null) {
            return element;
        }
    }
    List<Elements> selected = new ArrayList<Elements>();
    if (!CommonUtil.isEmpty(htmlNode.tagName)) {
        selected.add(body.getElementsByTag(htmlNode.tagName));
    } else if (!CommonUtil.isEmpty(htmlNode.href)) {
        selected.add(body.getElementsByTag("a"));
    }
    if (!CommonUtil.isEmpty(htmlNode.name)) {
        selected.add(body.getElementsByAttributeValue("name", htmlNode.name));
    }
    if (!CommonUtil.isEmpty(htmlNode.type)) {
        selected.add(body.getElementsByAttributeValue("type", htmlNode.type));
    }
    if (!CommonUtil.isEmpty(htmlNode.value)) {
        selected.add(body.getElementsByAttributeValue("value", htmlNode.value));
    }
    if (!CommonUtil.isEmpty(htmlNode.title)) {
        selected.add(body.getElementsByAttributeValue("title", htmlNode.title));
    }
    if (htmlNode.classes != null && htmlNode.classes.length > 0) {
        Map<Element, Integer> found = new HashMap<Element, Integer>();
        for (int i = 0; i < htmlNode.classes.length; i++) {
            Elements elements = body.getElementsByClass(htmlNode.classes[i]);
            for (Element element : elements) {
                if (!found.containsKey(element)) {
                    found.put(element, 0);
                }
                found.put(element, found.get(element) + 1);
            }
        }
        Elements elements = new Elements();
        for (int i = htmlNode.classes.length; i > 0; i--) {
            for (Map.Entry<Element, Integer> entry : found.entrySet()) {
                if (entry.getValue() == i) {
                    elements.add(entry.getKey());
                }
            }
            if (!elements.isEmpty()) {
                break;
            }
        }
        selected.add(elements);
    }
    if (!CommonUtil.isEmpty(htmlNode.href)) {
        Elements hrefs = body.getElementsByAttribute("href");
        Elements toAdd = new Elements();
        String currentUrl = driver.getCurrentUrl();
        String hrefGiven = htmlNode.href;
        for (Element href : hrefs) {
            String hrefFound = href.attr("href");
            if (hrefGiven.equalsIgnoreCase(hrefFound)) {
                toAdd.add(href);
            } else {
                String uriGiven = Util.toCanonicalUri(currentUrl, hrefGiven);
                String uriFound = Util.toCanonicalUri(currentUrl, hrefFound);
                if (uriGiven.equalsIgnoreCase(uriFound)) {
                    toAdd.add(href);
                }
            }
        }
        selected.add(toAdd);
    }
    if (!CommonUtil.isEmpty(htmlNode.innerText)) {
        selected.add(body.getElementsMatchingText(Pattern.quote(htmlNode.innerText)));
    }
    if (htmlNode.multiple != null) {
        selected.add(body.getElementsByAttribute("multiple"));
    }
    Map<Element, Integer> votes = new HashMap<Element, Integer>();
    for (Elements elements : selected) {
        for (Element element : elements) {
            if (!Util.isHidden(element)) {
                if (!votes.containsKey(element)) {
                    votes.put(element, 0);
                }
                votes.put(element, votes.get(element) + 1);
            }
        }
    }
    int maxVote = 0;
    Element maxElement = null;
    for (Map.Entry<Element, Integer> entry : votes.entrySet()) {
        if (entry.getValue() > maxVote) {
            maxVote = entry.getValue();
            maxElement = entry.getKey();
        }
    }
    return toElement(driver, maxElement);
}