UWP Webview将网页链接获取到数组中

4

我只能找到旧的过时答案,适用于UWP Win 10之前。我知道如何使用旧方法,但它给我带来了问题。

目前为止,我所做的是下面的内容,请注意问题似乎在VB中,因为它没有执行元素按标记名称命令,就像我被告知的那样。将其更改为inner HTML,然后它将使用完整页面填充html变量。因此,似乎我无法获取链接本身。

任何帮助都将不胜感激!谢谢!

XAML

<Page
    x:Class="webviewMessingAround.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:webviewMessingAround"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <WebView x:Name="webview" Source="http://regsho.finra.org/regsho-December.html" DOMContentLoaded="WebView_DOMContentLoaded" />
            <Button x:Name="button" HorizontalAlignment="Left" Margin="145,549,0,0" VerticalAlignment="Top">
                <Button x:Name="button1" Click="button_Click" Content="Button" Height="58" Width="141"/>
            </Button>
        </Grid>
    </Grid>
</Page>

VB代码

 Private Async Sub webview_DOMContentLoaded(sender As WebView, args As WebViewDOMContentLoadedEventArgs) Handles webview.DOMContentLoaded

        Dim html = Await webview.InvokeScriptAsync("eval", ({"document.getElementsByTagName('a');"}))

        'Debug.WriteLine(html)

    End Sub
1个回答

3
InvokeScriptAsync 只能返回脚本调用的字符串结果。

返回值

当此方法返回时,脚本调用的字符串结果。

如果您想从网页中获取链接,则需要将所有链接放入一个字符串中进行返回。以下是 C# 示例:

string html = await webview.InvokeScriptAsync("eval", new string[] { "[].map.call(document.getElementsByTagName('a'), function(node){ return node.href; }).join('||');" });
System.Diagnostics.Debug.WriteLine(html);

这里我使用:
[].map.call(document.getElementsByTagName('a'), function(node){ return node.href; }).join('||');

将所有链接放入一个字符串中。您可能需要更改此JavaScript代码来实现自己的目的。
之后,您可以像这样将字符串拆分为数组:
var links = html.Split(new[] { "||" }, StringSplitOptions.RemoveEmptyEntries);

虽然我使用的是C#作为示例,但VB代码应该类似。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接