【问题标题】:VB.Net Webview2 How can I get html source code?VB.Net Webview2 如何获取 html 源代码?
【发布时间】:2020-06-17 14:31:42
【问题描述】:

我成功地在我的 VB.net (Visual Studio 2017) 项目中的 WebView2 上显示了一个网站,但无法获取 html 源代码。请告诉我如何获取 html 代码。

我的代码:

Private Sub testbtn_Click(sender As Object, e As EventArgs) Handles testbtn.Click
        WebView2.CoreWebView2.Navigate("https://www.microsoft.com/")
End Sub

Private Sub WebView2_NavigationCompleted(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) Handles WebView2.NavigationCompleted
        Dim html As String = ?????
End Sub

确实感谢您提前提供的建议。

【问题讨论】:

标签: vb.net webview2


【解决方案1】:

我今天早些时候也刚刚开始使用 WebView2,并且只是在寻找同样的东西。我确实设法拼凑出这个解决方案:

Dim html As String
html = Await WebView2.ExecuteScriptAsync("document.documentElement.outerHTML;")

' The Html comes back with unicode character codes, other escaped characters, and
' wrapped in double quotes, so I'm using this code to clean it up for what I'm doing.
html = Regex.Unescape(html)
html = html.Remove(0, 1)
html = html.Remove(html.Length - 1, 1)

即时将我的代码从 C# 转换为 VB,因此希望不会遗漏任何语法错误。

【讨论】:

  • 太棒了。确实谢谢你。我可以完成从 WebView2 获取 html 源代码,如下面的代码所示。我真的很感激。 Private Sub testbtn_Click() Handles testbtn.Click wv.CoreWebView2.Navigate(""microsoft.com/"") End Sub Private Async Sub wv_NavigationCompleted() Handles wv.NavigationCompleted Dim html As String = String.Empty html = Await wv.ExecuteScriptAsync("document .documentElement.outerHTML;") html = Regex.Unescape(html) html = html.Remove(0, 1) html = html.Remove(html.Length - 1, 1) End Sub
【解决方案2】:

添加到@Xaviorq8 答案,您可以使用Span 摆脱使用Remove 生成新字符串:

html = Regex.Unescape(html)
html = html.AsSpan()[1..^1].ToString();

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 2012-04-22
    • 2011-03-03
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多