如何在c# webview中单击按钮 [英] how to click button in c# webview

查看:64
本文介绍了如何在c# webview中单击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 C# 程序,该程序将自动单击网页上的按钮.我知道我可以使用 chrome 驱动程序,但我不希望它变成浏览器和特定版本的应用程序.

I'm working on trying to write an c# program that will click a button on a webpage automatically. I know I could use a chrome driver, but I don't want this to turn into a browser and version specific application.

这是我目前想到的,但我很难确定如何在找到正确的按钮后触发该按钮被点击.

This is what I came up with so far, but I'm having some difficulty determining how to be able to trigger that button to be clicked once I have found the correct button.

    WebView webView = new WebView();
    var func = string.Format(@"document.getElementsByClassName('size-grid-button').innerText = '{0}';", size);            
    await webView.InvokeScriptAsync("eval", new string[] { func });

编辑这是我目前的项目基础,但我找不到基于innerText的按钮然后模拟按钮点击.

EDIT This is what I'm basing my project off currently, but I can't find a button based on innerText and then simulate button click.

推荐答案

这是一个使用 NuGet 包 Microsoft.Web.WebView2(v. 1.0.721-预发行版)的完整代码示例.有关要求,请参阅 Webview2 发行说明.

Here's a complete code example using NuGet package Microsoft.Web.WebView2 (v. 1.0.721-prerelease). See the Webview2 Release Notes for requirements.

资源:

注意:此示例将使用 WinForms--Windows Forms App (.NET Framework).使用 .NET Framework 时,支持版本 >= 4.6.2(以前需要 4.6.2 或更高版本.但是,如果查看 NuGet 包文件夹,似乎现在所需的最低版本可能是 4.5.参见有关更多信息,请参阅发行说明).请参阅其他受支持 SDK 的文档.

Note: This example will be using WinForms--Windows Forms App (.NET Framework). When using .NET Framework, versions >= 4.6.2 are supported (previously version 4.6.2 or greater was required. However, if one looks at the NuGet package folders, it appears that the required minimum version may now be 4.5. See the release notes for more information). See the documentation for other supported SDKs.

支持 Visual Studio 2017 和 2019 版.如果您没有,您可以下载 Visual Studio 社区 --这是免费的.

Visual Studio versions 2017 and 2019 are supported. If you don't have either, you may be able to Download Visual Studio Community -- which is free.

下载并安装 Microsoft Edge Dev(又名Dev Channel"):Microsoft Edge Insider Channels -- 有关其他选项,请参阅文档.

Download and install Microsoft Edge Dev (aka "Dev Channel"): Microsoft Edge Insider Channels -- see documentation for other options.

打开 Visual Studio -(2017 或 2019)

Open Visual Studio - (2017 or 2019)

默认包管理格式设置为PackageReference(这是可选的,但建议使用).请参阅从packages.config迁移到 PackageReference 了解更多信息.

Set Default package management format to PackageReference (this is optional, but recommended). See Migrate from packages.config to PackageReference for more information.

2019:

  • 点击无代码继续
  • 在 Visual Studio (VS) 菜单中,单击工具
  • 选择选项
  • 展开NuGet 包管理器
  • 点击常规
  • 包管理下,将默认包管理格式:设置为PackageReference
  • Click Continue without code
  • In Visual Studio (VS) menu, click Tools
  • Select Options
  • Expand NuGet Package Manager
  • Click General
  • Under Package Management, set Default package management format: to PackageReference

2017:

  • 在 Visual Studio (VS) 菜单中,单击工具
  • 选择选项
  • 展开NuGet 包管理器
  • 点击常规
  • 包管理下,将默认包管理格式:设置为PackageReference
  • In Visual Studio (VS) menu, click Tools
  • Select Options
  • Expand NuGet Package Manager
  • Click General
  • Under Package Management, set Default package management format: to PackageReference

创建新项目

2019:

  • 在 VS 菜单中,点击文件
  • 选择新建
  • 选择项目
  • 可选:使用以下选项来限制显示的选择:C#Windows 桌面
  • 点击Windows Forms App (.NET Framework)
  • 点击下一步
  • 为您的项目输入一个名称(例如:WebView2Test),选择所需的位置,然后将 Framework 设置为 >= 4.6.2
  • 点击创建

2017:

  • 在 VS 菜单中,点击文件
  • 选择新建
  • 选择项目
  • 展开Visual C#
  • 点击Windows 桌面
  • 点击Windows Forms App (.NET Framework)
  • 为您的项目输入一个名称(例如:WebView2Test),选择所需的位置,然后将 Framework 设置为 >= 4.6.2
  • 点击确定

Microsoft.Web.WebView2 NuGet 包添加到项目 (2019/2017)

Add Microsoft.Web.WebView2 NuGet package to project (2019/2017)

  • 在 VS 菜单中,点击查看
  • 选择解决方案资源管理器
  • 在解决方案资源管理器中,右键单击<项目名称>
  • 选择管理 NuGet包...
  • 点击浏览
  • 检查包括预发布
  • 搜索:Microsoft.Web.WebView2
  • 选择版本1.0.721-预发布
  • 通过单击左侧旁边的向下箭头来设置任何所需的选项选项"显示可用选项(即:安装和更新选项和卸载选项)
  • 点击安装
  • 如果弹出一个窗口,点击确定

可选:将 MenuStrip 添加到表单 (Form1)

Optional: Add MenuStrip to Form (Form1)

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 在 VS 菜单中,点击查看
  • 选择工具箱
  • 展开所有 Windows 窗体
  • 选择MenuStrip
  • 点击 Form (Form1) 将控件添加到 Form

可选:将 StatusStrip 添加到表单 (Form1)

Optional: Add StatusStrip to Form (Form1)

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 在 VS 菜单中,点击查看
  • 选择工具箱
  • 展开所有 Windows 窗体
  • 选择StatusStrip
  • 点击 Form (Form1) 将控件添加到 Form

将 SplitContainer 添加到表单 (Form1)

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 在 VS 菜单中,点击查看
  • 选择工具箱
  • 展开所有 Windows 窗体
  • 选择SplitContainer
  • 点击 Form (Form1) 将控件添加到 Form

将按钮添加到 SplitContainer (splitContainer1) 的左侧面板

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 在 VS 菜单中,点击查看
  • 选择工具箱
  • 展开所有 Windows 窗体
  • 选择按钮
  • 单击 Form (Form1) 将控件添加到 Form.如有必要,将按钮移至 SplitContainer 的左侧面板 (panel1).

更改按钮属性

  • 在 VS 菜单中,点击查看
  • 选择属性窗口
  • 在属性"窗口中,使用下拉菜单选择按钮 (button1)
  • 将(名称)更改为所需的名称(例如:btnClickJSButton)
  • 将文本更改为所需文本(例如:单击 JS 按钮)

将 WebView2 控件添加到 SplitContainer(panel2)

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 在 VS 菜单中,点击查看
  • 选择工具箱
  • 展开 WebView2 Windows 窗体控件
  • In Solution Explorer, click Form1.cs to select it
  • In VS menu, click View
  • Select Toolbox
  • Expand WebView2 Windows Forms Control

注意:如果WebView2 Windows 窗体控件"不在工具箱中,右键单击工具箱中的空白区域,然后选择选择项目".然后点击浏览".转到 %UserProfile%.nuget\packages\microsoft.web.webview2\1.0.721-prerelease\lib\net45(例如:C:\Users\<用户名>\.nuget\packages\microsoft.web.webview2\1.0.721-预发布\lib\net45).选择Microsoft.Web.WebView2.WinForms.dll"

Note: If "WebView2 Windows Forms Control" isn't in the Toolbox, right-click in an open space in the Toolbox, and select "Choose Items". Then click "Browse". Go to %UserProfile%.nuget\packages\microsoft.web.webview2\1.0.721-prerelease\lib\net45 (ex: C:\Users\<username>\.nuget\packages\microsoft.web.webview2\1.0.721-prerelease\lib\net45). Choose "Microsoft.Web.WebView2.WinForms.dll"

  • 选择WebView2
  • 单击 Form (Form1) 将控件添加到 Form.如有必要,将 WebView2 控件移动到 SplitContainer 的右侧面板 (panel2).

更改 WebView2 属性

  • 在属性窗口中,使用下拉菜单选择 WebView2 控件实例 (webView21)
  • 停靠属性设置为填充

向 Form 添加 Load 事件处理程序 (Form1)

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 双击 Form 顶部,将添加事件处理程序:Form1_Load

添加按钮点击事件处理程序

  • 在解决方案资源管理器中,单击 Form1.cs 以将其选中
  • 在 Form (Form1) 上,双击按钮 (btnClickJSButton),创建点击事件处理程序 (btnClickJSButton_Click)

为 HTML 代码创建一个文件夹

  • 在解决方案资源管理器中,右键单击<项目名称>
  • 选择添加
  • 选择新建文件夹.文件夹将被选中.如果没有,请右键单击该文件夹并选择重命名".将名称设置为HTML".
  • In Solution Explorer, right-click <project name>
  • Select Add
  • Select New Folder. The folder will be selected. If not, right-click the folder and select "Rename". Set the name to "HTML".

创建 index.html

  • 在解决方案资源管理器中,右键单击<项目名称>
  • 右键点击HTML文件夹
  • 选择添加
  • 选择新建项目
  • 点击HTML 页面(名称:index.html)
  • 点击添加
  • In Solution Explorer, right-click <project name>
  • Right-click HTML folder
  • Select Add
  • Select New Item
  • Click HTML Page (Name: index.html)
  • Click Add

更改 index.html 属性

  • 在解决方案资源管理器中,单击index.html 将其选中
  • 在属性窗口中,将 Build Action 设置为 Embedded Resource
  • In Solution Explorer, click index.html to select it
  • In Properties Window, set Build Action to Embedded Resource

添加代码到:index.html

Add code to: index.html

index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

    <script>
        function btnClickAction(name) {
            alert('button ' + name + ' was clicked');
        }
    </script>
</head>
<body>

    <button type="button" class="size-grid-button" id="size-grid-button1" onclick="btnClickAction('size-grid-button1')">Click Me 1</button>
    <button type="button" class="size-grid-button" id="size-grid-button2" onclick="btnClickAction('size-grid-button2')">Click Me 2</button>
    <button type="button" class="size-grid-button" id="size-grid-button3" onclick="btnClickAction('size-grid-button3')" value="Click Me 3">Click Me 3</button>

    <input type="button" class="size-grid-button" id="size-grid-button4" onclick="btnClickAction('size-grid-button4')" value="Click Me 4" />

</body>
</html>

为 JavaScript 代码创建一个文件夹

  • 在解决方案资源管理器中,右键单击<项目名称>
  • 选择添加
  • 选择新建文件夹.文件夹将被选中.如果没有,请右键单击该文件夹并选择重命名".将名称设置为JavaScript".
  • In Solution Explorer, right-click <project name>
  • Select Add
  • Select New Folder. The folder will be selected. If not, right-click the folder and select "Rename". Set the name to "JavaScript".

创建 TestButtonClick.js

  • 在解决方案资源管理器中,右键单击<项目名称>
  • 右键单击 JavaScript 文件夹
  • 选择添加
  • 选择新建项目
  • 点击JavaScript 文件(名称:TestButtonClick.js)
  • 点击添加
  • In Solution Explorer, right-click <project name>
  • Right-click JavaScript folder
  • Select Add
  • Select New Item
  • Click JavaScript File (Name: TestButtonClick.js)
  • Click Add

更改 TestButtonClick.js 属性

  • 在解决方案资源管理器中,单击 TestButtonClick.js 以将其选中
  • 在属性窗口中,将 Build Action 设置为 Embedded Resource
  • In Solution Explorer, click TestButtonClick.js to select it
  • In Properties Window, set Build Action to Embedded Resource

选项 1(所需的 HTML 元素是按钮")

Option 1 (desired HTML element is 'button')

示例:

<button type="button" class="size-grid-button" id="size-grid-button1" onclick="btnClickAction('size-grid-button1')">Click Me 1</button>

将代码添加到:TestButtonClick.js

Add code to: TestButtonClick.js

TestButtonClick.js(选项 1)

function clickDesiredButtonByInnerText(btnInnerText) {

    //let buttons = document.getElementByTagName('button');
    let buttons = document.querySelectorAll('button');
    let i = 0;
    let result = null;

    if (buttons) {
        
        for (i = 0; i < buttons.length; i++) {
            //window.chrome.webview.postMessage("button[" + i + "].innerText: " + buttons[i].innerText);

            if (buttons[i].innerText === btnInnerText) {
                buttons[i].click();
                result = btnInnerText + ' clicked';
                break; //exit loop
            }
        }
    }

    //window.chrome.webview.postMessage("result:" + result);
    return result;
}

选项 2(所需的 HTML 元素是输入")

Option 2 (desired HTML element is 'input')

示例:

<input type="button" class="size-grid-button" id="size-grid-button4" onclick="btnClickAction('size-grid-button4')" value="Click Me 4" />

将代码添加到:TestButtonClick.js

Add code to: TestButtonClick.js

TestButtonClick.js(选项 2)

function clickDesiredInputButtonByTextValue(btnValue) {

    let i = 0;
    let result = null;

    buttons = document.querySelectorAll('input');

    if (buttons) {

        for (i = 0; i < buttons.length; i++) {
            //window.chrome.webview.postMessage("button[" + i + "].value: " + buttons[i].value + ' type: ' + buttons[i].type);

            if (buttons[i].type === 'button' && buttons[i].value === btnValue) {
                buttons[i].click();
                result = btnValue + ' clicked';
                break; //exit loop
            }
        }
    }

    //window.chrome.webview.postMessage("result:" + result);
    return result;
}

选项 3(所需的 HTML 元素是 ('button' OR 'input') AND 元素具有一个具有唯一值的 'id' 属性)

Option 3 (desired HTML element is ('button' OR 'input') AND element has an 'id' attribute that has a unique value)

将代码添加到:TestButtonClick.js

Add code to: TestButtonClick.js

TestButtonClick.js(选项 3)

function clickDesiredButtonById(btnId) {
    let result = null;
    let desiredButton = document.getElementById(btnId);

    if (desiredButton) {
        desiredButton.click();
        result = 'button with id = ' + btnId + ' clicked';
    }

    //window.chrome.webview.postMessage("result:" + result);
    return result;
}

创建一个新类 (HelperLoadResource.cs)

Create a new class (HelperLoadResource.cs)

  • 在解决方案资源管理器中,右键单击<项目名称>
  • 选择添加
  • 选择类...(名称:HelperLoadResource.cs)
  • In Solution Explorer, right-click <project name>
  • Select Add
  • Select Class... (Name: HelperLoadResource.cs)

添加 using 语句(HelperLoadResource.cs):

Add using statements (HelperLoadResource.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using System.Diagnostics;

将代码添加到:HelperLoadResource.cs

Add code to: HelperLoadResource.cs

注意:HelperLoadResource.ReadResource 将从嵌入的文件(HTML 和 JavaScript)中读取文本并将文本放入字符串变量中.

Note: HelperLoadResource.ReadResource will read text from the embedded files (HTML and JavaScript) and put the text into a string variable.

HelperLoadResource.cs

public static class HelperLoadResource
{
    public static string ReadResource(string filename)
    {
        //use UTF8 encoding as the default encoding
        return ReadResource(filename, Encoding.UTF8);
    }

    public static string ReadResource(string filename, Encoding fileEncoding)
    {
        string fqResourceName = string.Empty;
        string result = string.Empty;

        //get executing assembly
        Assembly execAssembly = Assembly.GetExecutingAssembly();

        //get resource names
        string[] resourceNames = execAssembly.GetManifestResourceNames();

        if (resourceNames != null && resourceNames.Length > 0)
        {
            foreach (string rName in resourceNames)
            {
                if (rName.EndsWith(filename))
                {

                    //set value to 1st match
                    //if the same filename exists in different folders,
                    //the filename can be specified as <folder name>.<filename>
                    //or <namespace>.<folder name>.<filename>
                    fqResourceName = rName;

                    //exit loop
                    break;
                }
            }

            //if not found, throw exception
            if (String.IsNullOrEmpty(fqResourceName))
            {
                throw new Exception($"Resource '{filename}' not found.");
            }

            //get file text
            using (Stream s = execAssembly.GetManifestResourceStream(fqResourceName))
            {
                using (StreamReader reader = new StreamReader(s, fileEncoding))
                {
                    //get text
                    result = reader.ReadToEnd();
                }
            }
        }

        return result;
    }

}

将代码添加到:Form1.cs

  • 在解决方案资源管理器中,点击<项目名称>
  • 右键单击Form1.cs
  • 选择查看代码

添加 using 语句(Form1.cs):

Add using statements (Form1.cs):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Diagnostics;

添加方法 InitializeCoreWebView2Async (Form1.cs)

Add method InitializeCoreWebView2Async (Form1.cs)

InitializeCoreWebView2Async (Form1.cs)

InitializeCoreWebView2Async (Form1.cs)

private async Task InitializeCoreWebView2Async()
{
    //initialize CorewWebView2
    await webView21.EnsureCoreWebView2Async();
}

添加代码:Form1_Load (Form1.cs)

Add code to: Form1_Load (Form1.cs)

注意:将 async 关键字添加到 Form_Load.

Note: Add the async keyword to Form_Load.

Form1_Load (Form1.cs)

Form1_Load (Form1.cs)

private async void Form1_Load(object sender, EventArgs e)
{
    //show MS Edge version -- also ensures that an exception will be raised if proper MS Edge version isn't installed
    Debug.WriteLine(CoreWebView2Environment.GetAvailableBrowserVersionString());

    //initialized CorewWebView2
    await InitializeCoreWebView2Async();

    //get HTML
    string html = HelperLoadResource.ReadResource("index.html");
    
    //display HTML in WebView2
    webView21.NavigateToString(html);
    
}

订阅 WebView2 CoreWebView2InitializationCompleted 事件

Subscribe to WebView2 CoreWebView2InitializationCompleted event

  • 在属性窗口中,使用下拉菜单选择 WebView2 实例 (webView21)
  • 单击橙色闪电以查看可用事件
  • 双击 CoreWebView2InitializationCompleted 将事件处理程序添加到表单 (Form1.cs) 中
  • In Properties Window, use the drop-down to select the WebView2 instance (webView21)
  • Click the orange lightning bolt to see available events
  • Double-click CoreWebView2InitializationCompleted to add the event handler to the Form (Form1.cs)

将以下代码添加到 CoreWebView2InitializationCompleted

CoreWebView2InitializationCompleted (Form1.cs)

CoreWebView2InitializationCompleted (Form1.cs)

private void webView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e) 
{

    //subscribe to CoreWebView2 events (add event handlers)
    webView21.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;         
}

CoreWebView2_WebMessageReceived (Form1.cs)

CoreWebView2_WebMessageReceived (Form1.cs)

private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
    Debug.WriteLine("Info: MSG (JSON): " + e.WebMessageAsJson);
    Debug.WriteLine("Info: MSG (String): " + e.TryGetWebMessageAsString());
}

如果使用上面的选项 1(所需的 HTML 元素是按钮"),添加方法 ClickWebView2ButtonByInnerText

ClickWebView2ButtonByInnerText (Form1.cs)

ClickWebView2ButtonByInnerText (Form1.cs)

private async Task ClickWebView2ButtonByInnerText(string btnInnerText)
{
    if (webView21 != null && webView21.CoreWebView2 != null)
    {
        string jsCode = HelperLoadResource.ReadResource("TestButtonClick.js");
        jsCode += System.Environment.NewLine;
        jsCode += "clickDesiredButtonByInnerText('" + btnInnerText + "');";

        var result = await webView21.CoreWebView2.ExecuteScriptAsync(jsCode);

        Debug.WriteLine("result: " + result);
    }
}

将以下代码添加到按钮单击事件处理程序btnClickButton_Click(选项 1)

Add the following code to the Button click event handler btnClickButton_Click (Option 1)

注意:添加async关键字.

private async void btnClickButton_Click(object sender, EventArgs e)
{
    await ClickWebView2ButtonByInnerText("Click Me 3");
}

如果使用上面的选项 2(所需的 HTML 元素是 'input'),添加方法 ClickWebView2InputButton

ClickWebView2InputButton (Form1.cs)

ClickWebView2InputButton (Form1.cs)

private async Task ClickWebView2InputButton(string btnValue)
{
    if (webView21 != null && webView21.CoreWebView2 != null)
    {
        string jsCode = HelperLoadResource.ReadResource("TestButtonClick.js");
        jsCode += System.Environment.NewLine;
        jsCode += "clickDesiredInputButtonByTextValue('" + btnValue + "');";

        var result = await webView21.CoreWebView2.ExecuteScriptAsync(jsCode);

        Debug.WriteLine("result: " + result);
    }
}

将以下代码添加到按钮单击事件处理程序btnClickButton_Click(选项 2)

Add the following code to the Button click event handler btnClickButton_Click (Option 2)

注意:添加async关键字.

private async void btnClickButton_Click(object sender, EventArgs e)
{
    await ClickWebView2InputButton("Click Me 4");
}

如果使用上述选项 3(所需的 HTML 元素是 ('button' OR 'input') AND 元素具有具有唯一值的 'id' 属性),则添加方法 ClickWebView2ButtonById

ClickWebView2ButtonById (Form1.cs)

ClickWebView2ButtonById (Form1.cs)

private async Task ClickWebView2ButtonById(string btnId)
{
    if (webView21 != null && webView21.CoreWebView2 != null)
    {
        string jsCode = HelperLoadResource.ReadResource("TestButtonClick.js");
        jsCode += System.Environment.NewLine;
        jsCode += "clickDesiredButtonById('" + btnId + "');";

        var result = await webView21.CoreWebView2.ExecuteScriptAsync(jsCode);

        Debug.WriteLine("result: " + result);
    }
}

将以下代码添加到按钮单击事件处理程序btnClickButton_Click(选项 3)

Add the following code to the Button click event handler btnClickButton_Click (Option 3)

注意:添加async关键字.

private async void btnClickButton_Click(object sender, EventArgs e)
{
     await ClickWebView2ButtonById("size-grid-button2");
     await ClickWebView2ButtonById("size-grid-button4");
}

运行程序.点击表单上的按钮进行测试.

Run the program. Click the button on the form to test.

其他资源

这篇关于如何在c# webview中单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆