如何模拟点击以点击UWP中的网站按钮?

时间:2017-03-29 06:19:26

标签: c# uwp

我想学习如何模拟点击。例如,单击Bing中的“搜索”按钮。现在我已经在搜索框中分配了要搜索的值,但是如何模拟单击搜索按钮。

这是我的代码

NSString *urlString = @"http://www.yourWebAddress.com";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];

我知道如何在WPF上执行此操作。我想要一个等同于

的代码
private async void Button_ClickAsync(object sender, RoutedEventArgs e)
{
        var httpClint = new HttpClient();
        var elements = await httpClint.GetStringAsync(new Uri("https://www.bing.com/"));
        var htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(elements);
        var node1 = htmlDocument.DocumentNode.Descendants("input").Where(p => p.GetAttributeValue("class", "") == "b_searchbox").ToArray();
        node1[0].Attributes[5].Value = InputText.Text;            
        var node2 = htmlDocument.DocumentNode.Descendants("input").Where(p => p.GetAttributeValue("class", "") == "b_searchboxSubmit").ToArray();
}

表示UWP

1 个答案:

答案 0 :(得分:1)

你无法用HtmlDocument做你想做的事。这是一个静态HTML DOM树,其中javascript不活动。 在您的WPF中,您似乎使用的是webview control(webBrower1),而不是HTML文档。

UWP中的WPF WebBrowser等效于WebView。您可以从HTTP请求加载它并调用JS脚本。

您可以通过调用eval函数并将函数代码作为参数来调用页面中的脚本或任意JS代码。

在下面的代码中,我开始搜索单词' bing'一旦Bing主页加载。

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    webview.NavigationCompleted += OnNavigationCompleted;
    webview.Navigate(new Uri("http://www.bing.com"));
}

private async void OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    webview.NavigationCompleted -= OnNavigationCompleted;

    var inputValue = "Bing";

    var functionString = string.Format(@"document.getElementsByClassName('b_searchbox')[0].innerText = '{0}';
                                        document.getElementsByClassName('b_searchboxSubmit')[0].click();", inputValue);
    await webview.InvokeScriptAsync("eval", new string[] { functionString });
}