【解決方法】cefsharp ブラウザから HTML ファイルを取得する

プログラミングQA


やあみんな

cefsharp chromium を使用してブラウザーを作成し、html を保存するか、テキスト ボックスで開きたいと考えています。

試した:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    browser.ViewSource()
End Sub

そしてその後、htmlは私が望むように、ランダムな名前の一時データでメモ帳ファイルに出力されます。
exで自動保存したい。 「C:\」と name.htm (txt) または、テキスト ボックスで表示するか、tempdata でこの txt に含まれる名前を検索します。

解決策を見つけたいと思っています。助けてください。 ありがとう :)

私が試したこと:

Imports CefSharp.WinForms
Imports CefSharp

Public Class Form1

    Private WithEvents browser As ChromiumWebBrowser

    Public Sub New()
        InitializeComponent()

        Dim settings As New CefSettings
        CefSharp.Cef.Initialize(settings)

        browser = New ChromiumWebBrowser("url") With {
            .Dock = DockStyle.Fill
        }
        Panel1.Controls.Add(browser)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        browser.ViewSource()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        browser.Load(TextBox1.Text)
    End Sub

End Class

解決策 1

To get the HTML source code of a webpage loaded in a CefSharp browser control, you can use the GetSourceAsync method provided by the ChromiumWebBrowser control. Here's an example code snippet:

C#
using CefSharp;
using CefSharp.WinForms;
using System.Threading.Tasks;

namespace MyNamespace
{
    public class MyForm : Form
    {
        private ChromiumWebBrowser browser;

        // Constructor
        public MyForm()
        {
            // Initialize CefSharp settings
            var settings = new CefSettings();
            Cef.Initialize(settings);

            // Create browser control
            browser = new ChromiumWebBrowser("https://www.example.com");
            browser.Dock = DockStyle.Fill;
            Controls.Add(browser);

            // Attach an event handler to the browser control's LoadingStateChanged event
            browser.LoadingStateChanged += Browser_LoadingStateChanged;
        }

        // Event handler for browser control's LoadingStateChanged event
        private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            if (!e.IsLoading)
            {
                // Get the HTML source code of the loaded webpage
                string html = await browser.GetSourceAsync();
                // Do something with the HTML code
                Console.WriteLine(html);
            }
        }
    }
}
In this example, the GetSourceAsync method is called in the Browser_LoadingStateChanged event handler, which fires when the webpage finishes loading. The resulting HTML source code is stored in the html string variable, which can then be used as needed.

コメント

タイトルとURLをコピーしました