Visual Basic.NET - leer datos de una pagina web en vb.net

 
Vista:

leer datos de una pagina web en vb.net

Publicado por Rodolfo Velez (9 intervenciones) el 05/08/2010 16:05:14
¡¡¡¡¡ urgente !!!!!

hola a todos mi consulta es la siguien, estoy trabajando en una aplicacion que realiza una consulta a una paguina web pero ahora tengo que exptraer esos datos y mostrarlos en mi programa yo se que eso se puede hacer en vb 6.0 pero en vb.net no lo se

si me pueden ayudar con esto gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil

RE:leer datos de una pagina web en vb.net

Publicado por P. J. (706 intervenciones) el 17/08/2010 17:38:33
Como lo harias en vb 6.0 ???, si tienes el codigo ponlo aqui y en la comunidad te ayudaremos a trasladarlo al .net; o mejor aun importa la libreria Microsoft.Visual Basic y podras hacer uso desde el .net
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

transformar el codigoa .net datos de una pagina web en vb.net

Publicado por percy| (1 intervención) el 01/02/2016 14:38:14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Net;
using System.Collections.Specialized;
using System.IO;
 
namespace WindowsFormsApplication1
    //Primero tengo que obtener la librería HtmlAgilityPack que nos ayudara a manejar el 
    //HTML de la pagina web de SUNAT (http://www.sunat.gob.pe/cl-at-ittipcam/tcS01Alias). 
    //Para esto, descargamos la versión 1.4.6 de la pagina web del proyecto https://htmlagilitypack.codeplex.com/. 
    //Posteriormente, lo importamos como referencia en nuestro proyecto.
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //Ahora nos toca implementar el código que se encargará de conectarse a la pagina web y obtener el documento HTML.
                string sUrl = "http://www.sunat.gob.pe/cl-at-ittipcam/tcS01Alias";
                Encoding objEncoding = Encoding.GetEncoding("ISO-8859-1");
                CookieCollection objCookies = new CookieCollection();
 
                //USANDO GET
                HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(sUrl);
                getRequest.Method = "GET";
                getRequest.CookieContainer = new CookieContainer();
                getRequest.CookieContainer.Add(objCookies);
 
                //Como se puede ver usamos el Httpwebrequest para realizar la petición a la web de 
                //    SUNAT y con esto deberíamos obtener una respuesta que se cargara en el 
                //Httpwebresponse que se muestra continuación.
 
                string sGetResponse = string.Empty;
                using (HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse())
                {
                    objCookies = getResponse.Cookies;
                    using (StreamReader srGetResponse = new StreamReader(getResponse.GetResponseStream(), objEncoding))
                    {
                        sGetResponse = srGetResponse.ReadToEnd();
                    }
                }
                //Se ve que el resultado de la consulta se guarda en la variable sGetResponse y 
                //    esta contendrá el código HTML de la web de tipo de cambio. Con esta información 
                //        ya podremos saber cuales son los tipos de cambio de este mes pero nos faltaría 
                //obtener los valores de día, venta y compra sin los demás datos redundante del HTML. 
                //Para ello, usaremos la librería HtmlAgilityPack que ya tenemos en nuestro proyecto.
 
                //En este ejemplo se esta usando la libreria HtmlAgilityPack ... la pueden conseguir en internet
                //para el framework que deseen o que utilicen ... Go ! 
 
                //Obtenemos Informacion
                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(sGetResponse);
 
                //Como se puede apreciar, se ha cargado la variable sGetResponse, que contiene el
                //    código HTML, como  un objeto de tipo HtmlDocument. Con esto ya podemos navegar 
                //        entre los TAG'S HTML y poder quitar los datos redundante y solo obtener los que 
                //necesitamos. Estos datos los colocaremos en una tabla que contendrá 3 columnas (día, compra y venta).
 
                HtmlNodeCollection NodesTr = document.DocumentNode.SelectNodes("//table[@class='class=\"form-table\"']//tr");
 
 
                if (NodesTr != null)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("Dia", typeof(String));
                    dt.Columns.Add("Compra", typeof(String));
                    dt.Columns.Add("Venta", typeof(String));
                    int iNumFila = 0;
                    foreach (HtmlNode Node in NodesTr)
                    {
                        if (iNumFila > 0)
                        {
                            int iNumColumna = 0;
                            DataRow dr = dt.NewRow();
                            foreach (HtmlNode subNode in Node.Elements("td"))
                            {
                                if (iNumColumna == 0) dr = dt.NewRow();
                                string sValue = subNode.InnerHtml.ToString().Trim();
                                sValue = System.Text.RegularExpressions.Regex.Replace(sValue, "<.*?>", " ");
                                dr[iNumColumna] = sValue;
                                iNumColumna++;
                                if (iNumColumna == 3)
                                {
                                    dt.Rows.Add(dr);
                                    iNumColumna = 0;
                                }
                            }
                        }
                        iNumFila++;
                    }
                    dt.AcceptChanges();
                    // La idea es muy parecida (por no decir igual) a los otros proyectos colgados
                    //Suerte :)
                    this.dgvHtml.DataSource = dt;
                    //Obtener los ultimos valores es facil, porque esto devuelve una tabla y 
                    //pues obtenemos los datos de la ultima fila, en la linea de abajo se daran cuenta
                    // :)
                    label1.Text = dt.Rows[dt.Rows.Count-1].ItemArray[1].ToString();
                }
 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //Suscribanse y unsanse al grupo de facebook ! :)
        }
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Rafael
Val: 188
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

transformar el codigoa .net datos de una pagina web en vb.net

Publicado por Rafael (67 intervenciones) el 09/11/2016 07:21:26
MI AMIGO BUEN DIA FIJATE QUE YO TENGO UN DETALLE CON MI CODIGO YA QUE NO PUEDO OBTENER DATOS Y REDIRECCIONARLOS CON EL METODO POST PARA INGRESAR A LA PAGINA DEL SAT Y SELECCIONAR QUE TIPOS DE XML DESCARGAR, ESPERO ME PUEDAS AYUDAR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
'INIT
        lblMensaje.Text = "Inicializando.."
        Dim tempCookie As New CookieContainer()
        Dim postData As String = "option=credential&Ecom_User_ID=" + txtUsuario.Text + "&Ecom_Password=" + txtPassword.Text + "&submit=Enviar"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
 
        'OBTENEMOS LA COOKIE
        lblMensaje.Text = "Obteniendo la Cookie.."
        Dim peticionGalleta As HttpWebRequest = CType(WebRequest.Create("https://cfdiau.sat.gob.mx/nidp/app/login?id=SATUPCFDiCon&sid=0&option=credential&sid=0"), HttpWebRequest)
        peticionGalleta.Method = "POST"
        peticionGalleta.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        'peticionGalleta.ContentType = "text/html;charset=UTF-8";
        peticionGalleta.CookieContainer = tempCookie
        peticionGalleta.Host = "cfdiau.sat.gob.mx"
        peticionGalleta.Referer = "https://cfdiau.sat.gob.mx/nidp/wsfed/ep?id=SATx509Custom&sid=0&option=credential&sid=0"
        peticionGalleta.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
        'peticionGalleta.ContentLength = byteArray.Length;
 
        Dim sw As New StreamWriter(peticionGalleta.GetRequestStream())
        sw.Write(postData, 0, byteArray.Length)
        sw.Close()
 
        Dim respuestaGalleta As HttpWebResponse = CType(peticionGalleta.GetResponse(), HttpWebResponse)
        Dim lectorGalleta As New StreamReader(respuestaGalleta.GetResponseStream())
        Dim htmlr As String = lectorGalleta.ReadToEnd()
        richTextBox1.Text = htmlr
        WebBrowser1.DocumentText = richTextBox1.Text
 
 
        'YA CON LA COOKIE INICIAMOS SESION  
        lblMensaje.Text = "Iniciando Sesion.."
        Dim peticion As HttpWebRequest = CType(WebRequest.Create("https://cfdiau.sat.gob.mx/nidp/app/login?sid=0&sid=0"), HttpWebRequest)
        peticion.Method = "POST"
        peticion.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        peticion.Credentials = CredentialCache.DefaultCredentials
        peticion.KeepAlive = True
        peticion.CookieContainer = tempCookie
        peticion.Host = "cfdiau.sat.gob.mx"
        peticion.Referer = "https://cfdiau.sat.gob.mx//nidp/app/login?id=SATUPCFDiCon&sid=0&option=credential&sid=0"
        peticion.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
        peticion.ContentType = "application/x-www-form-urlencoded"
        peticion.ContentLength = byteArray.Length
 
        Dim sw2 As New StreamWriter(peticion.GetRequestStream())
        sw2.Write(postData, 0, byteArray.Length)
        sw2.Close()
 
        'OBTENEMOS INGRESO
        lblMensaje.Text = "Obteniendo Datos.."
        Dim respuesta As HttpWebResponse = CType(peticion.GetResponse(), HttpWebResponse)
        Dim lector As New StreamReader(respuesta.GetResponseStream())
        Dim html As String = lector.ReadToEnd()
 
        richTextBox1.Text = html
        WebBrowser1.DocumentText = richTextBox1.Text
 
        'OBTENEMOS DATOS PARA REFERENCIAR
        lblMensaje.Text = "Iniciando Tipo.."
        Dim peticionTIPOD As HttpWebRequest = CType(WebRequest.Create("https://portalcfdi.facturaelectronica.sat.gob.mx/"), HttpWebRequest)
        peticionTIPOD.Method = "POST"
        peticionTIPOD.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        peticionTIPOD.Credentials = CredentialCache.DefaultCredentials
        peticionTIPOD.KeepAlive = True
        peticionTIPOD.CookieContainer = tempCookie
        peticionTIPOD.Host = "portalcfdi.facturaelectronica.sat.gob.mx"
        peticionTIPOD.Referer = "https://cfdicontribuyentes.accesscontrol.windows.net/v2/wsfederation"
        peticionTIPOD.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
        peticionTIPOD.ContentType = "application/x-www-form-urlencoded"
        ''peticionTIPOD.ContentLength = byteArray.Length
 
        Dim sw3 As New StreamWriter(peticionTIPOD.GetRequestStream())
        sw3.Write(postData, 0, byteArray.Length)
        sw3.Close()
 
        'OBTENEMOS CONTROL DE ACCESO
        lblMensaje.Text = "Obteniendo Tipos.."
        Dim respuesta3 As HttpWebResponse = CType(peticionTIPOD.GetResponse(), HttpWebResponse)
        Dim lector3 As New StreamReader(respuesta3.GetResponseStream())
        'OBTIENE RESPUESTA FORM EN STRING
        Dim html3 As String = lector3.ReadToEnd()
        ''ELIMINO LA CEDENA <META HTTP-EQUIV="expires" CONTENT="0"> PARA CONVERTIR RESPUESTA EN XML
        Dim CadenaEliminar = "<META HTTP-EQUIV=" & """expires""" & " CONTENT=" & """0""" & ">"
        html3 = Replace(html3, CadenaEliminar, "")
        ''Leemos los valores pasando la respuesta XML a un DataSet
        Dim srXmlData As New System.IO.StringReader(html3)
        Dim DS As New DataSet
        DS.ReadXml(srXmlData)
        Rwa = DS.Tables("input").Rows(0).Item("value")
        Rwresult = DS.Tables("input").Rows(1).Item("value")
        Rwctx = DS.Tables("input").Rows(2).Item("value")
 
        richTextBox1.Text = html3
        WebBrowser1.DocumentText = richTextBox1.Text
 
 
 
        ''MUESTRA TIPO DE DESCARGA
        Dim postDataA As String = "wa=" & Rwa & "&wresult=" & Rwresult & "&wctx=" & Rwctx
        Dim byteArrayA As Byte() = Encoding.UTF8.GetBytes(postDataA)
 
        'lblMensaje.Text = "Iniciando Tipo.."
        Dim Peticion4 As HttpWebRequest = CType(WebRequest.Create("https://cfdicontribuyentes.accesscontrol.windows.net/v2/wsfederation"), HttpWebRequest)
        Peticion4.Method = "POST"
        ''Peticion4.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        'Peticion4.Credentials = CredentialCache.DefaultCredentials
        Peticion4.AllowAutoRedirect = True
        ''Peticion4.KeepAlive = True
        ''Peticion4.CookieContainer = tempCookie
        ''Peticion4.Host = "cfdicontribuyentes.accesscontrol.windows.net"
        ''Peticion4.Referer = "https://cfdiau.sat.gob.mx/nidp/app/login?sid=0&sid=0"
        Peticion4.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"
        ''Peticion4.ContentType = "application/x-www-form-urlencoded"
        Peticion4.ContentLength = byteArrayA.Length
 
 
        'Dim sw4 As New StreamWriter(Peticion4.GetRequestStream())
        'sw4.Write(postDataA, 0, byteArrayA.Length)
        'sw4.Close()
 
        Dim requestStream As Stream = Peticion4.GetRequestStream
        Dim postBytes As Byte() = Encoding.ASCII.GetBytes(postDataA)
        requestStream.Write(postBytes, 0, postBytes.Length)
        requestStream.Close()
 
 
        'OBTENEMOS SALDO Y VIGENCIA
        lblMensaje.Text = "Obteniendo Tipos.."
        Dim respuesta4 As HttpWebResponse = CType(Peticion4.GetResponse(), HttpWebResponse)
        Dim lector4 As New StreamReader(respuesta4.GetResponseStream())
        Dim html4 As String = lector4.ReadToEnd()
 
        richTextBox1.Text = html4
        WebBrowser1.DocumentText = richTextBox1.Text

CABE MENCIONAR QUE RICHTEXBO Y EL WEBBROWSER SOLO SON REFERENCIA DE QUE MARCHE BIEN EL CODIGO, SALUDOS.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

transformar el codigoa .net datos de una pagina web en vb.net

Publicado por cesar (1 intervención) el 28/11/2016 17:30:12
buenos días y gracias Percy por tu codigo en C# aun no se mucho pero de C# pero me gustaría saber si lo puedes transformar el código a VB.net al parecer lo hice en un ejemplo de C# y funciona genial pero a la hora de transformar a VB ahí soy nulo. por favor tu ayuda o alguien del foro..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Net;
using System.Collections.Specialized;
using System.IO;
 
namespace WindowsFormsApplication1
    //Primero tengo que obtener la librería HtmlAgilityPack que nos ayudara a manejar el 
    //HTML de la pagina web de SUNAT (http://www.sunat.gob.pe/cl-at-ittipcam/tcS01Alias). 
    //Para esto, descargamos la versión 1.4.6 de la pagina web del proyecto https://htmlagilitypack.codeplex.com/. 
    //Posteriormente, lo importamos como referencia en nuestro proyecto.
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //Ahora nos toca implementar el código que se encargará de conectarse a la pagina web y obtener el documento HTML.
                string sUrl = "http://www.sunat.gob.pe/cl-at-ittipcam/tcS01Alias";
                Encoding objEncoding = Encoding.GetEncoding("ISO-8859-1");
                CookieCollection objCookies = new CookieCollection();
 
                //USANDO GET
                HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(sUrl);
                getRequest.Method = "GET";
                getRequest.CookieContainer = new CookieContainer();
                getRequest.CookieContainer.Add(objCookies);
 
                //Como se puede ver usamos el Httpwebrequest para realizar la petición a la web de 
                //    SUNAT y con esto deberíamos obtener una respuesta que se cargara en el 
                //Httpwebresponse que se muestra continuación.
 
                string sGetResponse = string.Empty;
                using (HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse())
                {
                    objCookies = getResponse.Cookies;
                    using (StreamReader srGetResponse = new StreamReader(getResponse.GetResponseStream(), objEncoding))
                    {
                        sGetResponse = srGetResponse.ReadToEnd();
                    }
                }
                //Se ve que el resultado de la consulta se guarda en la variable sGetResponse y 
                //    esta contendrá el código HTML de la web de tipo de cambio. Con esta información 
                //        ya podremos saber cuales son los tipos de cambio de este mes pero nos faltaría 
                //obtener los valores de día, venta y compra sin los demás datos redundante del HTML. 
                //Para ello, usaremos la librería HtmlAgilityPack que ya tenemos en nuestro proyecto.
 
                //En este ejemplo se esta usando la libreria HtmlAgilityPack ... la pueden conseguir en internet
                //para el framework que deseen o que utilicen ... Go ! 
 
                //Obtenemos Informacion
                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(sGetResponse);
 
                //Como se puede apreciar, se ha cargado la variable sGetResponse, que contiene el
                //    código HTML, como  un objeto de tipo HtmlDocument. Con esto ya podemos navegar 
                //        entre los TAG'S HTML y poder quitar los datos redundante y solo obtener los que 
                //necesitamos. Estos datos los colocaremos en una tabla que contendrá 3 columnas (día, compra y venta).
 
                HtmlNodeCollection NodesTr = document.DocumentNode.SelectNodes("//table[@class='class=\"form-table\"']//tr");
 
 
                if (NodesTr != null)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("Dia", typeof(String));
                    dt.Columns.Add("Compra", typeof(String));
                    dt.Columns.Add("Venta", typeof(String));
                    int iNumFila = 0;
                    foreach (HtmlNode Node in NodesTr)
                    {
                        if (iNumFila > 0)
                        {
                            int iNumColumna = 0;
                            DataRow dr = dt.NewRow();
                            foreach (HtmlNode subNode in Node.Elements("td"))
                            {
                                if (iNumColumna == 0) dr = dt.NewRow();
                                string sValue = subNode.InnerHtml.ToString().Trim();
                                sValue = System.Text.RegularExpressions.Regex.Replace(sValue, "<.*?>", " ");
                                dr[iNumColumna] = sValue;
                                iNumColumna++;
                                if (iNumColumna == 3)
                                {
                                    dt.Rows.Add(dr);
                                    iNumColumna = 0;
                                }
                            }
                        }
                        iNumFila++;
                    }
                    dt.AcceptChanges();
                    // La idea es muy parecida (por no decir igual) a los otros proyectos colgados
                    //Suerte :)
                    this.dgvHtml.DataSource = dt;
                    //Obtener los ultimos valores es facil, porque esto devuelve una tabla y 
                    //pues obtenemos los datos de la ultima fila, en la linea de abajo se daran cuenta
                    // :)
                    label1.Text = dt.Rows[dt.Rows.Count-1].ItemArray[1].ToString();
                }
 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //Suscribanse y unsanse al grupo de facebook ! :)
        }
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar