How do I capture text from a HTML element given its id="" from a WebView2 in VB.NET?

Viewed 25

I am trying to read a table and get the fields i need from that table with Webview2.

Table markup

I am able to get the source code of the webpage but I'm stumped beyond that.

    Private Async Function WebView2_NavigationCompletedAsync(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) As Task Handles WebView21.NavigationCompleted
        Dim html As String
        html = Await WebView21.ExecuteScriptAsync("document.documentElement.outerHTML;")
        html = Regex.Unescape(html)
        html = html.Remove(0, 1)
        html = html.Remove(html.Length - 1, 1)

    End Function
1 Answers
  1. Use document.getElementById to get a reference to a DOM element.
  2. Then use textContent or innerText to get the text (not HTML) of that element (and all its descendants) stitched together.
    • Use textContent to get text from all descendant elements, including hidden and <script> elements.
    • Use innerText to filter-out hidden elements and non-human-readable elements.
  3. As you cannot directly interact with the DOM in WebView2 you will need to do it all in JavaScript inside ExecuteScriptAsync. The result of the last expression inside the script will be converted to a .NET String value and returned via the Task<String> which you can await.

Like so:

Private Async Function WebView2_NavigationCompletedAsync( ... ) As Task
    Handles WebView21.NavigationCompleted

    '''''

    Dim firstNameText As String = Await WebView21.ExecuteScriptAsync("document.getElementById('m.first_name').textContent");

    MessageBox.Show( "First name: """ & firstNameText & """." )

End Function
Related