gpt4 book ai didi

c# - 从 CefSharp 网络浏览器获取 HTML 源代码

转载 作者:可可西里 更新时间:2023-11-01 08:20:50 26 4
gpt4 key购买 nike

我正在使用 aCefSharp.Wpf.ChromiumWebBrowser(版本 47.0.3.0)加载网页。页面加载后的某个时刻,我想获取源代码。

我打过:

wb.GetBrowser().MainFrame.GetSourceAsync()

但是它似乎并没有返回所有源代码(我相信这是因为有子框架)。

如果我调用:

wb.GetBrowser().MainFrame.ViewSource() 

我可以看到它列出了所有源代码(包括内部框架)。

我想获得与 ViewSource() 相同的结果。请有人指出我正确的方向吗?

更新 – 添加了代码示例

注意:网络浏览器指向的地址也只能在 10/03/2016 之前有效。之后它可能会显示不同的数据,这不是我想要看到的。

在 frmSelection.xaml 文件中

<cefSharp:ChromiumWebBrowser Name="wb" Grid.Column="1" Grid.Row="0" />

在 frmSelection.xaml.cs 文件中

public partial class frmSelection : UserControl
{
private System.Windows.Threading.DispatcherTimer wbTimer = new System.Windows.Threading.DispatcherTimer();

public frmSelection()
{

InitializeComponent();

// This timer will start when a web page has been loaded.
// It will wait 4 seconds and then call wbTimer_Tick which
// will then see if data can be extracted from the web page.
wbTimer.Interval = new TimeSpan(0, 0, 4);
wbTimer.Tick += new EventHandler(wbTimer_Tick);

wb.Address = "http://www.racingpost.com/horses2/cards/card.sd?race_id=644222&r_date=2016-03-10#raceTabs=sc_";

wb.FrameLoadEnd += new EventHandler<CefSharp.FrameLoadEndEventArgs>(wb_FrameLoadEnd);

}

void wb_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
{
if (wbTimer.IsEnabled)
wbTimer.Stop();

wbTimer.Start();
}

void wbTimer_Tick(object sender, EventArgs e)
{
wbTimer.Stop();
string html = GetHTMLFromWebBrowser();
}

private string GetHTMLFromWebBrowser()
{
// call the ViewSource method which will open up notepad and display the html.
// this is just so I can compare it to the html returned in GetSourceAsync()
// This is displaying all the html code (including child frames)
wb.GetBrowser().MainFrame.ViewSource();

// Get the html source code from the main Frame.
// This is displaying only code in the main frame and not any child frames of it.
Task<String> taskHtml = wb.GetBrowser().MainFrame.GetSourceAsync();

string response = taskHtml.Result;
return response;
}

}

最佳答案

我不认为我完全理解这个 DispatcherTimer 解决方案。我会这样做:

public frmSelection()
{
InitializeComponent();

wb.FrameLoadEnd += WebBrowserFrameLoadEnded;
wb.Address = "http://www.racingpost.com/horses2/cards/card.sd?race_id=644222&r_date=2016-03-10#raceTabs=sc_";
}

private void WebBrowserFrameLoadEnded(object sender, FrameLoadEndEventArgs e)
{
if (e.Frame.IsMain)
{
wb.ViewSource();
wb.GetSourceAsync().ContinueWith(taskHtml =>
{
var html = taskHtml.Result;
});
}
}

我对 ViewSource 的输出和 html 变量中的文本进行了比较,它们是相同的,所以我无法在这里重现您的问题。

这就是说,我注意到主框架的加载时间很晚,所以您必须等待一段时间,直到记事本弹出源代码。

关于c# - 从 CefSharp 网络浏览器获取 HTML 源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com