用java语言实现webbrowser,在类库中使用WebBrowser进行Web抓取

本文探讨了在C#中通过WebBrowser控件抓取动态加载内容时遇到的问题,如ActiveX控件无法实例化的错误。作者提供了一个尝试的代码片段,并询问是否有解决方法或现成的库可以用来获取动态Web内容。问题集中在多线程环境和异步操作上。
摘要由CSDN通过智能技术生成

我需要在类库中创建一个方法来获取URL的内容(可以通过JavaScript动态填充) .

我很无能,但谷歌搜索了一整天这是我提出的:(大部分代码来自here)

using System;

using System.Threading.Tasks;

using System.Threading;

using System.Windows.Forms;

public static class WebScraper

{

[STAThread]

public async static Task LoadDynamicPage(string url, CancellationToken token)

{

using (WebBrowser webBrowser = new WebBrowser())

{

// Navigate and await DocumentCompleted

var tcs = new TaskCompletionSource();

WebBrowserDocumentCompletedEventHandler onDocumentComplete = (s, arg) => tcs.TrySetResult(true);

using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))

{

webBrowser.DocumentCompleted += onDocumentComplete;

try

{

webBrowser.Navigate(url);

await tcs.Task; // wait for DocumentCompleted

}

finally

{

webBrowser.DocumentCompleted -= onDocumentComplete;

}

}

// get the root element

var documentElement = webBrowser.Document.GetElementsByTagName("html")[0];

// poll the current HTML for changes asynchronosly

var html = documentElement.OuterHtml;

while (true)

{

// wait asynchronously, this will throw if cancellation requested

await Task.Delay(500, token);

// continue polling if the WebBrowser is still busy

if (webBrowser.IsBusy)

continue;

var htmlNow = documentElement.OuterHtml;

if (html == htmlNow)

break; // no changes detected, end the poll loop

html = htmlNow;

}

// consider the page fully rendered

token.ThrowIfCancellationRequested();

return html;

}

}

}

它目前抛出此错误

ActiveX控件'8856f961-340a-11d0-a96b-00c04fd705a2'无法实例化,因为当前线程不在单线程单元中 .

我接近了吗?上面有解决方法吗?

或者如果我不在轨道上,是否有一个现成的解决方案来使用.NET获取动态Web内容(可以从类库中调用)?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值