Search code examples
vb.netwebbrowser-controlcurrency

Reading Numbers from Webbrowser Vb.net


In my WebBrowser I got text like this: Remaining balance: 10$
I would like to convert it to another currency, I want just to read number from my browser, then after that I will send it to a Label or TextBox with the new converted currency. I am stuck here.
A screenshot of it

Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
    WebBrowser2.Navigate(TextBox9.Text + TextBox2.Text)
End Sub
Private Sub WebBrowser2_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser2.DocumentCompleted
    Label1.Text = (WebBrowser2.Document.Body.InnerText)
End Sub

Solution


  • I have this suggestion (I know this is probably not the perfect solution):

    1. First, try loading that same webpage in a normal web browser such as Google Chrome or Firefox or any browser which has the feature to "inspect elements", meaning to view their HTML code.
    2. Find out the element which displays the price you want.
    3. Note down the ID of the element (usually written something like id="someID")
    4. Back to your program's code, include the following Function, which will get the text displayed and convert it to another currency:

      Public Function ConvertDisplayedCurrency() As Decimal
          Dim MyCurrencyElement As HtmlElement = WebBrowser2.Document.GetElementById("theIdYouGotInStep3") 'This will refer to the element you want.
          Dim TheTextDisplayed As String = MyCurrencyElement.InnerText 'This will refer to the text that is displayed.
          'Assuming that the text begins like "Remaining balance: ###", you need to strip off that first part, which is "Remaining balance: ".
          Dim TheNumberDisplayed As String = TheTextDisplayed.Substring(19)
          'The final variable TheNumberDisplayed will be resulting into a String like only the number.
          Dim ParsedNumber As Decimal = 0 'A variable which will be used below.
          Dim ParseSucceeded As Boolean = Decimal.TryParse(TheNumberDisplayed, ParsedNumber)
          'The statement above will TRY converting the String TheNumberDisplayed to a Decimal.
          'If it succeeds, the number will be set to the variable ParsedNumber and the variable
          'ParseSucceeded will be True. If the conversion fails, the ParseSucceeded will be set
          'to False.
          If Not ParseSucceeded = True Then Return 0 : Exit Function 'This will return 0 and quit the Function if the parse was a failure.
      
          'Now here comes your turn. Write your own statements to convert the number "ParsedNumber"
          'to your new currency and finally write "Return MyFinalVariableName" in the end.
      
      End Function
      
    5. Call that Function probably when the document of the WebBrowser2 loads, that is, in the WebBrowser2_DocumentCompleted sub.

    I hope it helps!