elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Parsear código HTML en Vb.net
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Parsear código HTML en Vb.net  (Leído 3,856 veces)
#Aitor

Desconectado Desconectado

Mensajes: 173



Ver Perfil
Parsear código HTML en Vb.net
« en: 12 Mayo 2014, 18:08 pm »

Hola buenas, acostumbrado de PHP y su forma de parsear código.

Código
  1. preg_match_all('<b>Ejemplo de parsear, este numero es variante (.*) </b>', $ejemplo, $ejemplo1);

con el (.*) se obtenia el valor que se encontraba ahí. No encuentro una manera eficiente de hacerlo en VB.net

Mejor dicho no encuentro nada de información sobre cómo hacerlo en Vb.net, y la única solución que encuentro es haciéndolo de forma muy absurda.

Código
  1. Dim valor as integer = InStr(codigo_html.Text, "<b>Ejemplo de parsear, este numero es variante")

y a partir de ahí guardar la última posición en un entero (valor) y recorrer un for hasta que encuentre un "<" y salga de éste, como digo, me parece muy ineficiente y absurda.

¿Existe alguna 'mejor' forma, más cómoda de parsear?


En línea

Mi algoritmo en PHP (estupideces y más).
Código
  1. while($Se_feliz){
  2.  Piensa_un_OBJETIVO(); // Sin excusas!
  3.  if($Tienes_un_objetivo){
  4.    Suspira(); // Sé paciente.
  5.    if($Consigues_el_objetivo){ echo "¡Felicidades #Aitor!";return;
  6.      //RETURN; ¿O volvemos a empezar?
  7.    }else{
  8.      Inténtalo_de_nuevo();
  9.    }
  10.  }
  11. }
.:Weeds:.

Desconectado Desconectado

Mensajes: 122



Ver Perfil
Re: Parsear código HTML en Vb.net
« Respuesta #1 en: 18 Mayo 2014, 00:07 am »

Tal vez esto sea lo que buscas.

http://htmlagilitypack.codeplex.com/

Hay muchos tutoriales en google sobre como usarlo.

Saludos.


En línea


Eleкtro
Ex-Staff
*
Conectado Conectado

Mensajes: 9.808



Ver Perfil
Re: Parsear código HTML en Vb.net
« Respuesta #2 en: 28 Junio 2014, 04:02 am »

He leido en un post tuyo más reciente que comentabas la falta de atención a este post, lo digo porque de lo contrario no respondería a un post de antiguedad por no ser un buen ejemplo...



Para ser sinceros, el compañero @.:Weeds:.te ha sugerido la mejor opción que hay, pero es una librería demasiado completa y amplia para tus necesidades, lo cual resolverías descargando el source y usando un simple RegEx.

De todas formas, te dejo un ejemplo que escribí hace tiempo sobre el uso de dicha librería, espero que te sirva en algo:

Código
  1. Public Class Form1
  2.  
  3.    Private ReadOnly html As String =
  4.        <a><![CDATA[
  5. <!DOCTYPE html>
  6. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  7. <body>
  8.  
  9. <div class="infolinks"><input type="hidden" name="IL_IN_TAG" value="1"/></div><div id="main">
  10.  
  11. <div class="music">
  12.  
  13. <h2 class="boxtitle">New releases \ <small>
  14. <a href="/newalbums" title="New releases mp3 downloads" rel="bookmark">see all</a></small>
  15. </h2>
  16.  
  17. <div class="item">
  18.  
  19.     <div class="thumb">
  20. <a href="http://www.mp3crank.com/curt-smith/deceptively-heavy-121861" rel="bookmark" lang="en" title="Curt Smith - Deceptively Heavy album downloads"><img width="100" height="100" alt="Mp3 downloads Curt Smith - Deceptively Heavy" title="Free mp3 downloads Curt Smith - Deceptively Heavy" src="http://www.mp3crank.com/cover-album/Curt-Smith-Deceptively-Heavy-400x400.jpg"/></a>
  21.     </div>
  22.  
  23. <div class="release">
  24. <h3>Curt Smith</h3>
  25. <h4>
  26. <a href="http://www.mp3crank.com/curt-smith/deceptively-heavy-121861" title="Mp3 downloads Curt Smith - Deceptively Heavy">Deceptively Heavy</a>
  27. </h4>
  28. <script src="/ads/button.js"></script>
  29. </div>
  30.  
  31. <div class="release-year">
  32. <p>Year</p>
  33. <span>2013</span>
  34. </div>
  35.  
  36. <div class="genre">
  37. <p>Genre</p>
  38. <a href="http://www.mp3crank.com/genre/indie" rel="tag">Indie</a><a href="http://www.mp3crank.com/genre/pop" rel="tag">Pop</a>
  39. </div>
  40.  
  41. </div>
  42.  
  43. <div class="item">
  44.  
  45.     <div class="thumb">
  46. <a href="http://www.mp3crank.com/wolf-eyes/lower-demos-121866" rel="bookmark" lang="en" title="Wolf Eyes - Lower Demos album downloads"><img width="100" height="100" alt="Mp3 downloads Wolf Eyes - Lower Demos" title="Free mp3 downloads Wolf Eyes - Lower Demos" src="http://www.mp3crank.com/cover-album/Wolf-Eyes-–-Lower-Demos.jpg" /></a>
  47.     </div>
  48.  
  49. <div class="release">
  50. <h3>Wolf Eyes</h3>
  51. <h4>
  52. <a href="http://www.mp3crank.com/wolf-eyes/lower-demos-121866" title="Mp3 downloads Wolf Eyes - Lower Demos">Lower Demos</a>
  53. </h4>
  54. <script src="/ads/button.js"></script>
  55. </div>
  56.  
  57. <div class="release-year">
  58. <p>Year</p>
  59. <span>2013</span>
  60. </div>
  61.  
  62. <div class="genre">
  63. <p>Genre</p>
  64. <a href="http://www.mp3crank.com/genre/rock" rel="tag">Rock</a>
  65. </div>
  66.  
  67. </div>
  68.  
  69. </div>
  70.  
  71. </div>
  72.  
  73. </body>
  74. </html>
  75. ]]$cdataend$</a>.Value
  76.  
  77.    Private sb As New System.Text.StringBuilder
  78.  
  79.    Private htmldoc As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument
  80.    Private htmlnodes As HtmlAgilityPack.HtmlNodeCollection = Nothing
  81.  
  82.    Private Title As String = String.Empty
  83.    Private Cover As String = String.Empty
  84.    Private Year As String = String.Empty
  85.    Private Genres As String() = {String.Empty}
  86.    Private URL As String = String.Empty
  87.  
  88.    Private Sub Test() Handles MyBase.Shown
  89.  
  90.        ' Load the html document.
  91.        htmldoc.LoadHtml(html)
  92.  
  93.        ' Select the (10 items) nodes.
  94.        ' All "SelectSingleNode" below will use this DIV element as a starting point.
  95.        htmlnodes = htmldoc.DocumentNode.SelectNodes("//div[@class='item']")
  96.  
  97.        ' Loop trough the nodes.
  98.        For Each node As HtmlAgilityPack.HtmlNode In htmlnodes
  99.  
  100.             ' Set the values:
  101.            Title = node.SelectSingleNode(".//div[@class='release']/h4/a[@title]").GetAttributeValue("title", "Unknown Title")
  102.            Cover = node.SelectSingleNode(".//div[@class='thumb']/a/img[@src]").GetAttributeValue("src", String.Empty)
  103.            Year = node.SelectSingleNode(".//div[@class='release-year']/span").InnerText
  104.            Genres = (From genre In node.SelectNodes(".//div[@class='genre']/a") Select genre.InnerText).ToArray
  105.            URL = node.SelectSingleNode(".//div[@class='release']/h4/a[@href]").GetAttributeValue("href", "Unknown URL")
  106.  
  107.            ' Display the values:
  108.            sb.Clear()
  109.            sb.AppendLine(String.Format("Title : {0}", Title))
  110.            sb.AppendLine(String.Format("Cover : {0}", Cover))
  111.            sb.AppendLine(String.Format("Year  : {0}", Year))
  112.            sb.AppendLine(String.Format("Genres: {0}", String.Join(", ", Genres)))
  113.            sb.AppendLine(String.Format("URL   : {0}", URL))
  114.            MsgBox(sb.ToString)
  115.  
  116.        Next node
  117.  
  118.    End Sub
  119.  
  120. End Class
  121.  


+ Como descargar el source de una página:

Código
  1.    ' Get SourcePage Array
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' Dim SourceLines As String() = GetSourcePageArray("http://www.ElHacker.net", TrimLines:=True)
  6.    ' For Each Line As String In SourceLines : MsgBox(Line) : Next Line
  7.    '
  8.    ''' <summary>
  9.    ''' Gets a web source page.
  10.    ''' </summary>
  11.    ''' <param name="URL">Indicates the source page URL to get.</param>
  12.    ''' <param name="TrimLines">Indicates whether to trim the lines.</param>
  13.    ''' <param name="SplitOptions">Indicates the split options.</param>
  14.    ''' <returns>System.String[][].</returns>
  15.    ''' <exception cref="Exception"></exception>
  16.    Private Function GetSourcePageArray(ByVal URL As String,
  17.                                        Optional ByVal TrimLines As Boolean = False,
  18.                                        Optional ByVal SplitOptions As StringSplitOptions =
  19.                                                       StringSplitOptions.None) As String()
  20.  
  21.        Try
  22.  
  23.            Using StrReader As New IO.StreamReader(Net.HttpWebRequest.Create(URL).GetResponse().GetResponseStream)
  24.  
  25.                If TrimLines Then
  26.  
  27.                    Return (From Line As String
  28.                           In StrReader.ReadToEnd.Split({Environment.NewLine}, SplitOptions)
  29.                           Select Line.Trim).ToArray
  30.  
  31.                Else
  32.                    Return StrReader.ReadToEnd.Split({Environment.NewLine}, SplitOptions)
  33.  
  34.                End If
  35.  
  36.            End Using
  37.  
  38.        Catch ex As Exception
  39.            Throw New Exception(ex.Message)
  40.            Return Nothing
  41.  
  42.        End Try
  43.  
  44.    End Function

+ Un breve ejemplo de la utilización de un RegEx:

Código
  1. #Region " RegEx Match Tag "
  2.  
  3.    ' [ RegEx Match Tag Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Dim str As String = <a><![CDATA[href=>Drifter - In Search of Something More [EP] (2013)</a>]]></a>.Value
  9.    ' MsgBox(RegEx_Match_Tag(str, 1)) ' Result: Drifter - In Search of Something More [EP] (2013)
  10.  
  11.    Private Function RegEx_Match_Tag(ByVal str As String, Optional ByVal Group As Int32 = 0) As String
  12.  
  13.        ' Match criteria:
  14.        '
  15.        ' >Text<
  16.  
  17.        Dim RegEx As New System.Text.RegularExpressions.Regex( _
  18.        <a><![CDATA[>([^<]+?)<]]$cdataend$</a>.Value)
  19.  
  20.        Return RegEx.Match(str).Groups(Group).ToString
  21.  
  22.    End Function
  23.  
  24. #End Region


Saludos
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Parsear html, ¿algo sencillo?
Java
Ragnarok 3 9,247 Último mensaje 5 Junio 2007, 18:20 pm
por alvk4r
Parsear HTML con PHP – Simple HTML DOM Parser
PHP
madpitbull_99 3 15,132 Último mensaje 1 Abril 2014, 09:54 am
por BlackM4ster
Parsear con PHP Simple HTML DOM
PHP
multi-media asdfg 5 6,082 Último mensaje 16 Julio 2011, 01:20 am
por multi-media asdfg
Parsear HTML ayuda !!!
.NET (C#, VB.NET, ASP)
TrashAmbishion 4 2,815 Último mensaje 8 Julio 2012, 18:50 pm
por TrashAmbishion
Parsear HTML
.NET (C#, VB.NET, ASP)
spiritdead 2 2,666 Último mensaje 26 Diciembre 2012, 23:55 pm
por spiritdead
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines