I need to take the value of the dollar, from a web page, since I need it to be constantly updated, to multiply certain products by the value of the dollar.
For example on this page: link
Greetings, Tutee.
The technique you're looking for is called HTML Parsing
, which allows you to get the elements of any web page in the HTML DOM
model.
On the internet you find some parser
, however I was testing (since my strength is not vb.net) without downloading anything and the way it worked was using a WebBrowser
(no need to add it to the form ).
This is the code, in the end I will explain some details:
Public Class Form1
Dim web As WebBrowser 'Aquí se declara el WebBrowser
Private Sub cargarPagina()
web = New WebBrowser() ' Se instancia el WebBrower
web.ScriptErrorsSuppressed = True ' Oculta la ventana de errores si algún script de la página falló (de todas formas no los necesitamos)
web.Navigate(New Uri("https://www.precio-dolar.com.ar/")) ' Carga la página web creando un nuevo documento HTML
' Este Handler permite continuar con el proceso una vez que se ha cargado TODA la página (ya que si no ha cargado lanzará un error)
AddHandler web.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf cargarValorDolar)
End Sub
Private Sub cargarValorDolar()
If (web.Document IsNot Nothing) Then ' En caso de que la página no halla cargado bien el documento
Dim divs = web.Document.Body.GetElementsByTagName("div") ' Obtiene todos los elementos <div> de la página web
For Each div As HtmlElement In divs ' Recorre la lista de elementos <div>
Dim className As String = div.GetAttribute("className") ' Obtiene el atributo [class] (nos servirá de filtro)
If className = "currency-field-result" Then ' El texto con el que se compara es el que muestra el valor del dólar en pesos argentinos
Label1.Text = div.InnerText ' Se obtiene el valor del dólar
End If
Next
End If
End Sub
End Class
Basically, what is done is a search 'filter' between all <div>
elements found on that web page by means of className
which corresponds to: "currency-field-result"
.
Here I leave the result:
The disadvantage of doing it this way is that it could vary according to the web page, you would have to manually modify the way you will 'filter' the results.
You could use a webservice of the ones in the network, HERE you have an article talking about it, maybe it's the simplest and most reliable option.
But as I see that you use .NET you can also do it by downloading the HTML code of the page that you indicate through its URL and reading the text value locating the tag that has the value (that is concretely a div that has this class "currency" -field-result "). The only problem with this is that they change the HTML code of the page ..
HERE you have an example of how to download an HTML page from your URL
I hope it serves you