Manipulação avançada de String

8 respostas
Baroni

Estou usando a seguinte instrução para recuperar o HTML de um site:

try {
        URL url = new URL("http://www.google.com.br");
    
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {

        }
        in.close();
    } catch (IOException e) {
    }

A variável str vai conter uma string com o código HTML do site, no caso o google.com.br.

Agora eu preciso editar essa string pegando partes específicas desse código HTML e transformar em variáveis para o meu sistema.
Por exemplo, supondo que o site tenha a seguinte tabela:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Página de exemplo</title>
    <meta http-equiv="Content-Type" content="text/html;" />
</head>
<body bgcolor="#ffffff" style="font-family: Arial">
    <div align="center">
        <table>
            <tr>
                <td colspan="2">
                    <table width="100%" border="0" align="center" cellpadding="50">
                        <tr>
                            <td align="left">
                                <table width="100%" border="1" bgcolor="#E8E8E8" bordercolor="#EBEBEB">
                                    <tr align="center" bgcolor="#E8E8E8">
                                        <td>
                                            <font size="2"><b>Servi&ccedil;o</b></font></td>
                                        <td>
                                            <font size="2"><b>Descri&ccedil;&atilde;o</b></font></td>

                                        <td>
                                            <font size="2"><b>M&ecirc;s/Ref.</b></font></td>
                                    </tr>
                                    <tr align="center" bgcolor="#FFFFFF">
                                        <td>
                                            <font size="2">
                                                01.01.01
                                            </font>

                                        </td>
                                        <td>
                                            <font size="2">
                                                RETIRANDO A VEGETACAO, TRONCOS ATE 5CM DE DIAMETRO E RASPAGEM
                                            </font>
                                        </td>
                                        <td>
                                            <font size="2">
                                                12/2008
                                            </font>

                                        </td>
                                    </tr>
                                </table>
                                <table border="1" bgcolor="#E8E8E8" bordercolor="fbfbfb" style="width: 100%">
                                    <tr align="middle" bgcolor="#E8E8E8">
                                        <td>
                                            <font size="2"><b>C&oacute;digo</b></font></td>
                                        <td>

                                            <font size="2"><b>Descri&ccedil;&atilde;o</b></font></td>
                                        <td>
                                            <font size="2"><b>Unidade</b></font></td>
                                        <td>
                                            <font size="2"><b>Coeficiente</b></font></td>
                                        <td>
                                            <font size="2"><b>Pre&ccedil;o</b></font></td>

                                        <td>
                                            <font size="2"><b>Sub Total</b></font></td>
                                    </tr>
                                    
                                    <tr bgcolor="#FFFFFF">
                                        <td align="middle">
                                            <font size="2">
                                                10.146
                                            </font>
                                        </td>

                                        <td>
                                            <font size="2">
                                                SERVENTE
                                            </font>
                                        </td>
                                        <td align="middle">
                                            <font size="2">
                                                H 
                                            </font>
                                        </td>

                                        <td align="right">
                                            <font size="2">
                                                0,25000
                                            </font>
                                        </td>
                                        <td align="right">
                                            <font size="2">
                                                3,28
                                            </font>
                                        </td>

                                        <td align="right">
                                            <font size="2">
                                                0,82000
                                            </font>
                                        </td>
                                    </tr>
                                    
                                </table>
                                <br />
                                <table cellspacing="1" cellpadding="1" width="100%" border="1" bgcolor="#FFFFF0"
                                    bordercolor="fbfbfb">

                                    <tr>
                                        <td bgcolor="#E8E8E8">
                                            <font size="2"><b>M&atilde;o Obra:</b></font></td>
                                        <td bgcolor="#FFFFFF">
                                            <font size="2">
                                                0,82000
                                            </font>
                                        </td>

                                        <td bgcolor="#E8E8E8">
                                            <font size="2"><b>*LS:</b></font></td>
                                        <td bgcolor="#FFFFFF">
                                            <font size="2">
                                                1,00040
                                            </font>
                                        </td>
                                        <td bgcolor="#E8E8E8">
                                            <font size="2"><b>SubMO:</b></font></td>

                                        <td bgcolor="#FFFFFF">
                                            <font size="2">
                                                1,82040
                                            </font>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td bgcolor="#E8E8E8">
                                            <font size="2"><b>Materiais:</b></font></td>

                                        <td bgcolor="#FFFFFF">
                                            <font size="2">
                                                0,00000
                                            </font>
                                        </td>
                                        <td bgcolor="#E8E8E8">
                                            <font size="2"><b>*BDI:</b></font></td>
                                        <td bgcolor="#FFFFFF">
                                            <font size="2">

                                                0,41869
                                            </font>
                                        </td>
                                        <td bgcolor="#E8E8E8">
                                            <font size="2"><b>TOTAL:</b></font></td>
                                        <td bgcolor="#FFFFFF">
                                            <font size="2">
                                                2,23000
                                            </font>

                                        </td>
                                    </tr>
                                </table>
                                <font size="2">
                                    <br />
                                    *LS - Leis Sociais<br>
                                    *BDI - Benef&iacute;cios e Despesas Indiretas</font>

                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

Supondo que minha variável str tenha assumido esse código como seu conteúdo e eu precisasse, por exemplo, recuperar o valor "01.01.01", que está no código acima, como eu faria?

E se eu não conhecesse o valor "01.01.01" nem o seu tamanho (por exemplo se eu precisasse recuperar o valor da "Descrição" sendo essa descrição de tamanho variável e conteúdo desconhecido, representado nesse exemplo pela string "RETIRANDO A VEGETACAO, TRONCOS ATE 5CM DE DIAMETRO E RASPAGEM", como eu deveria proceder?

E, por último, vocês tem alguma dica sobre esse código para ler o HTML de um site?

Até mais!

8 Respostas

mateusprado

Ola Baroni!

De uma olhada em http://jtidy.sourceforge.net/ , isso vai te ajudar.

[ ]s,

Vini_Fernandes

Entao Baroni, se entendi bem, o que voce deseja é reconhecer alguns padroes de uma string e recuperar informações quando o padrão é encontrado, resumindo, o que deseja será resolvido utilizando Expressões Regulares. Para isso voce pode utilizar as classes java.util.regex.Pattern e java.util.regex.Match. Na API da Pattern tem um monte de informação sobre como construir suas expressões regulares. Aqui no fórum temos um artigo a respeito:

http://www.guj.com.br/article.show.logic?id=1

Ate mais

Vini_Fernandes

Cara, segue um exemplo pra vc:

// Fig. 29.24: RegexMatches.java
// Demonstrating Classes Pattern and Matcher.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
   public static void main( String args[] )
   {
      // create regular expression
      Pattern expression = 
         Pattern.compile( "J.*\d[0-35-9]-\d\d-\d\d" );
      
      String string1 = "Jane's Birthday is 05-12-75\n" +
         "Dave's Birthday is 11-04-68\n" +
         "John's Birthday is 04-28-73\n" +
         "Joe's Birthday is 12-17-77";

      // match regular expression to string and print matches
      Matcher matcher = expression.matcher( string1 );
        
      while ( matcher.find() )
         System.out.println( matcher.group() );
   } // end main
} // end class RegexMatches


/*
 **************************************************************************
 * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. All Rights Reserved.                           *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 **************************************************************************
*/
mateusprado

Regex ajudariam sim em alguns cassos, porem no caso dele ainda vejo o http://jtidy.sourceforge.net/ como melhor opção.

[ ]s,

Vini_Fernandes

Cara, nao conhecia JTidy! Aprendi mais uma…

Valeu!!

Baroni

mateusprado:
Ola Baroni!

De uma olhada em http://jtidy.sourceforge.net/ , isso vai te ajudar.

[ ]s,

Mateus,

Eu tentei, estudei, patinei e não sai do lugar… Não entendi NADA do JTidy… :lol:

Você ou algum outro usuário que “manje” de JTidy poderiam me dar uma “mãozinha” por favor??? Um manual seria MUITO bem vindo… Aceito também soluções alternativas… Caso alguém se habilite :smiley:

Sou newba de mais para aprender essas coisas sozinho ainda… :cry:

Até mais!

B

É possível você alterar esse HTML para um XML+XSL+CSS?

Recuperar dados de HTML é bruto demais…

Baroni

Infelizmente não Bruno

Criado 9 de maio de 2009
Ultima resposta 20 de mai. de 2009
Respostas 8
Participantes 4